xref: /llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision 3f78605a8cb121d005c0ad11cce83cf58be983f2)
1 //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a pass to prepare loops for ppc preferred addressing
10 // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
11 // update)
12 // Additional PHIs are created for loop induction variables used by load/store
13 // instructions so that preferred addressing modes can be used.
14 //
15 // 1: DS/DQ form preparation, prepare the load/store instructions so that they
16 //    can satisfy the DS/DQ form displacement requirements.
17 //    Generically, this means transforming loops like this:
18 //    for (int i = 0; i < n; ++i) {
19 //      unsigned long x1 = *(unsigned long *)(p + i + 5);
20 //      unsigned long x2 = *(unsigned long *)(p + i + 9);
21 //    }
22 //
23 //    to look like this:
24 //
25 //    unsigned NewP = p + 5;
26 //    for (int i = 0; i < n; ++i) {
27 //      unsigned long x1 = *(unsigned long *)(i + NewP);
28 //      unsigned long x2 = *(unsigned long *)(i + NewP + 4);
29 //    }
30 //
31 // 2: D/DS form with update preparation, prepare the load/store instructions so
32 //    that we can use update form to do pre-increment.
33 //    Generically, this means transforming loops like this:
34 //    for (int i = 0; i < n; ++i)
35 //      array[i] = c;
36 //
37 //    to look like this:
38 //
39 //    T *p = array[-1];
40 //    for (int i = 0; i < n; ++i)
41 //      *++p = c;
42 //===----------------------------------------------------------------------===//
43 
44 #define DEBUG_TYPE "ppc-loop-instr-form-prep"
45 
46 #include "PPC.h"
47 #include "PPCSubtarget.h"
48 #include "PPCTargetMachine.h"
49 #include "llvm/ADT/DepthFirstIterator.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/Statistic.h"
54 #include "llvm/Analysis/LoopInfo.h"
55 #include "llvm/Analysis/ScalarEvolution.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/IR/BasicBlock.h"
58 #include "llvm/IR/CFG.h"
59 #include "llvm/IR/Dominators.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/IntrinsicsPowerPC.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/InitializePasses.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Transforms/Scalar.h"
73 #include "llvm/Transforms/Utils.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include "llvm/Transforms/Utils/Local.h"
76 #include "llvm/Transforms/Utils/LoopUtils.h"
77 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
78 #include <cassert>
79 #include <iterator>
80 #include <utility>
81 
82 using namespace llvm;
83 
84 // By default, we limit this to creating 16 common bases out of loops per
85 // function. 16 is a little over half of the allocatable register set.
86 static cl::opt<unsigned> MaxVarsPrep("ppc-formprep-max-vars",
87                                  cl::Hidden, cl::init(16),
88   cl::desc("Potential common base number threshold per function for PPC loop "
89            "prep"));
90 
91 static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
92                                  cl::init(true), cl::Hidden,
93   cl::desc("prefer update form when ds form is also a update form"));
94 
95 // Sum of following 3 per loop thresholds for all loops can not be larger
96 // than MaxVarsPrep.
97 // By default, we limit this to creating 9 PHIs for one loop.
98 // 9 and 3 for each kind prep are exterimental values on Power9.
99 static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
100                                  cl::Hidden, cl::init(3),
101   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
102            "form"));
103 
104 static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
105                                  cl::Hidden, cl::init(3),
106   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
107 
108 static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
109                                  cl::Hidden, cl::init(3),
110   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
111 
112 
113 // If would not be profitable if the common base has only one load/store, ISEL
114 // should already be able to choose best load/store form based on offset for
115 // single load/store. Set minimal profitable value default to 2 and make it as
116 // an option.
117 static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
118                                     cl::Hidden, cl::init(2),
119   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
120            "preparation"));
121 
122 STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
123 STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
124 STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
125 STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
126 STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
127 STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
128 
129 namespace {
130   struct BucketElement {
131     BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
132     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
133 
134     const SCEVConstant *Offset;
135     Instruction *Instr;
136   };
137 
138   struct Bucket {
139     Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
140                                             Elements(1, BucketElement(I)) {}
141 
142     const SCEV *BaseSCEV;
143     SmallVector<BucketElement, 16> Elements;
144   };
145 
146   // "UpdateForm" is not a real PPC instruction form, it stands for dform
147   // load/store with update like ldu/stdu, or Prefetch intrinsic.
148   // For DS form instructions, their displacements must be multiple of 4.
149   // For DQ form instructions, their displacements must be multiple of 16.
150   enum InstrForm { UpdateForm = 1, DSForm = 4, DQForm = 16 };
151 
152   class PPCLoopInstrFormPrep : public FunctionPass {
153   public:
154     static char ID; // Pass ID, replacement for typeid
155 
156     PPCLoopInstrFormPrep() : FunctionPass(ID) {
157       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
158     }
159 
160     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
161       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
162     }
163 
164     void getAnalysisUsage(AnalysisUsage &AU) const override {
165       AU.addPreserved<DominatorTreeWrapperPass>();
166       AU.addRequired<LoopInfoWrapperPass>();
167       AU.addPreserved<LoopInfoWrapperPass>();
168       AU.addRequired<ScalarEvolutionWrapperPass>();
169     }
170 
171     bool runOnFunction(Function &F) override;
172 
173   private:
174     PPCTargetMachine *TM = nullptr;
175     const PPCSubtarget *ST;
176     DominatorTree *DT;
177     LoopInfo *LI;
178     ScalarEvolution *SE;
179     bool PreserveLCSSA;
180 
181     /// Successful preparation number for Update/DS/DQ form in all inner most
182     /// loops. One successful preparation will put one common base out of loop,
183     /// this may leads to register presure like LICM does.
184     /// Make sure total preparation number can be controlled by option.
185     unsigned SuccPrepCount;
186 
187     bool runOnLoop(Loop *L);
188 
189     /// Check if required PHI node is already exist in Loop \p L.
190     bool alreadyPrepared(Loop *L, Instruction* MemI,
191                          const SCEV *BasePtrStartSCEV,
192                          const SCEVConstant *BasePtrIncSCEV,
193                          InstrForm Form);
194 
195     /// Collect condition matched(\p isValidCandidate() returns true)
196     /// candidates in Loop \p L.
197     SmallVector<Bucket, 16>
198     collectCandidates(Loop *L,
199                       std::function<bool(const Instruction *, const Value *)>
200                           isValidCandidate,
201                       unsigned MaxCandidateNum);
202 
203     /// Add a candidate to candidates \p Buckets.
204     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
205                          SmallVector<Bucket, 16> &Buckets,
206                          unsigned MaxCandidateNum);
207 
208     /// Prepare all candidates in \p Buckets for update form.
209     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
210 
211     /// Prepare all candidates in \p Buckets for displacement form, now for
212     /// ds/dq.
213     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
214                       InstrForm Form);
215 
216     /// Prepare for one chain \p BucketChain, find the best base element and
217     /// update all other elements in \p BucketChain accordingly.
218     /// \p Form is used to find the best base element.
219     /// If success, best base element must be stored as the first element of
220     /// \p BucketChain.
221     /// Return false if no base element found, otherwise return true.
222     bool prepareBaseForDispFormChain(Bucket &BucketChain,
223                                      InstrForm Form);
224 
225     /// Prepare for one chain \p BucketChain, find the best base element and
226     /// update all other elements in \p BucketChain accordingly.
227     /// If success, best base element must be stored as the first element of
228     /// \p BucketChain.
229     /// Return false if no base element found, otherwise return true.
230     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
231 
232     /// Rewrite load/store instructions in \p BucketChain according to
233     /// preparation.
234     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
235                            SmallSet<BasicBlock *, 16> &BBChanged,
236                            InstrForm Form);
237   };
238 
239 } // end anonymous namespace
240 
241 char PPCLoopInstrFormPrep::ID = 0;
242 static const char *name = "Prepare loop for ppc preferred instruction forms";
243 INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
244 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
245 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
246 INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
247 
248 static constexpr StringRef PHINodeNameSuffix    = ".phi";
249 static constexpr StringRef CastNodeNameSuffix   = ".cast";
250 static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
251 static constexpr StringRef GEPNodeOffNameSuffix = ".off";
252 
253 FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
254   return new PPCLoopInstrFormPrep(TM);
255 }
256 
257 static bool IsPtrInBounds(Value *BasePtr) {
258   Value *StrippedBasePtr = BasePtr;
259   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
260     StrippedBasePtr = BC->getOperand(0);
261   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
262     return GEP->isInBounds();
263 
264   return false;
265 }
266 
267 static std::string getInstrName(const Value *I, StringRef Suffix) {
268   assert(I && "Invalid paramater!");
269   if (I->hasName())
270     return (I->getName() + Suffix).str();
271   else
272     return "";
273 }
274 
275 static Value *GetPointerOperand(Value *MemI) {
276   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
277     return LMemI->getPointerOperand();
278   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
279     return SMemI->getPointerOperand();
280   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
281     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
282         IMemI->getIntrinsicID() == Intrinsic::ppc_mma_lxvp)
283       return IMemI->getArgOperand(0);
284     if (IMemI->getIntrinsicID() == Intrinsic::ppc_mma_stxvp)
285       return IMemI->getArgOperand(1);
286   }
287 
288   return nullptr;
289 }
290 
291 bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
292   if (skipFunction(F))
293     return false;
294 
295   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
296   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
297   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
298   DT = DTWP ? &DTWP->getDomTree() : nullptr;
299   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
300   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
301   SuccPrepCount = 0;
302 
303   bool MadeChange = false;
304 
305   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
306     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
307       MadeChange |= runOnLoop(*L);
308 
309   return MadeChange;
310 }
311 
312 void PPCLoopInstrFormPrep::addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
313                                         SmallVector<Bucket, 16> &Buckets,
314                                         unsigned MaxCandidateNum) {
315   assert((MemI && GetPointerOperand(MemI)) &&
316          "Candidate should be a memory instruction.");
317   assert(LSCEV && "Invalid SCEV for Ptr value.");
318   bool FoundBucket = false;
319   for (auto &B : Buckets) {
320     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
321     if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
322       B.Elements.push_back(BucketElement(CDiff, MemI));
323       FoundBucket = true;
324       break;
325     }
326   }
327 
328   if (!FoundBucket) {
329     if (Buckets.size() == MaxCandidateNum)
330       return;
331     Buckets.push_back(Bucket(LSCEV, MemI));
332   }
333 }
334 
335 SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
336     Loop *L,
337     std::function<bool(const Instruction *, const Value *)> isValidCandidate,
338     unsigned MaxCandidateNum) {
339   SmallVector<Bucket, 16> Buckets;
340   for (const auto &BB : L->blocks())
341     for (auto &J : *BB) {
342       Value *PtrValue;
343       Instruction *MemI;
344 
345       if (LoadInst *LMemI = dyn_cast<LoadInst>(&J)) {
346         MemI = LMemI;
347         PtrValue = LMemI->getPointerOperand();
348       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(&J)) {
349         MemI = SMemI;
350         PtrValue = SMemI->getPointerOperand();
351       } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(&J)) {
352         if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
353             IMemI->getIntrinsicID() == Intrinsic::ppc_mma_lxvp) {
354           MemI = IMemI;
355           PtrValue = IMemI->getArgOperand(0);
356         } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_mma_stxvp) {
357           MemI = IMemI;
358           PtrValue = IMemI->getArgOperand(1);
359         } else continue;
360       } else continue;
361 
362       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
363       if (PtrAddrSpace)
364         continue;
365 
366       if (L->isLoopInvariant(PtrValue))
367         continue;
368 
369       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
370       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
371       if (!LARSCEV || LARSCEV->getLoop() != L)
372         continue;
373 
374       if (isValidCandidate(&J, PtrValue))
375         addOneCandidate(MemI, LSCEV, Buckets, MaxCandidateNum);
376     }
377   return Buckets;
378 }
379 
380 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
381                                                     InstrForm Form) {
382   // RemainderOffsetInfo details:
383   // key:            value of (Offset urem DispConstraint). For DSForm, it can
384   //                 be [0, 4).
385   // first of pair:  the index of first BucketElement whose remainder is equal
386   //                 to key. For key 0, this value must be 0.
387   // second of pair: number of load/stores with the same remainder.
388   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
389 
390   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
391     if (!BucketChain.Elements[j].Offset)
392       RemainderOffsetInfo[0] = std::make_pair(0, 1);
393     else {
394       unsigned Remainder =
395           BucketChain.Elements[j].Offset->getAPInt().urem(Form);
396       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
397         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
398       else
399         RemainderOffsetInfo[Remainder].second++;
400     }
401   }
402   // Currently we choose the most profitable base as the one which has the max
403   // number of load/store with same remainder.
404   // FIXME: adjust the base selection strategy according to load/store offset
405   // distribution.
406   // For example, if we have one candidate chain for DS form preparation, which
407   // contains following load/stores with different remainders:
408   // 1: 10 load/store whose remainder is 1;
409   // 2: 9 load/store whose remainder is 2;
410   // 3: 1 for remainder 3 and 0 for remainder 0;
411   // Now we will choose the first load/store whose remainder is 1 as base and
412   // adjust all other load/stores according to new base, so we will get 10 DS
413   // form and 10 X form.
414   // But we should be more clever, for this case we could use two bases, one for
415   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and 1
416   // X form.
417   unsigned MaxCountRemainder = 0;
418   for (unsigned j = 0; j < (unsigned)Form; j++)
419     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
420         RemainderOffsetInfo[j].second >
421             RemainderOffsetInfo[MaxCountRemainder].second)
422       MaxCountRemainder = j;
423 
424   // Abort when there are too few insts with common base.
425   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
426     return false;
427 
428   // If the first value is most profitable, no needed to adjust BucketChain
429   // elements as they are substracted the first value when collecting.
430   if (MaxCountRemainder == 0)
431     return true;
432 
433   // Adjust load/store to the new chosen base.
434   const SCEV *Offset =
435       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
436   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
437   for (auto &E : BucketChain.Elements) {
438     if (E.Offset)
439       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
440     else
441       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
442   }
443 
444   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
445             BucketChain.Elements[0]);
446   return true;
447 }
448 
449 // FIXME: implement a more clever base choosing policy.
450 // Currently we always choose an exist load/store offset. This maybe lead to
451 // suboptimal code sequences. For example, for one DS chain with offsets
452 // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
453 // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
454 // multipler of 4, it cannot be represented by sint16.
455 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
456   // We have a choice now of which instruction's memory operand we use as the
457   // base for the generated PHI. Always picking the first instruction in each
458   // bucket does not work well, specifically because that instruction might
459   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
460   // the choice is somewhat arbitrary, because the backend will happily
461   // generate direct offsets from both the pre-incremented and
462   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
463   // instruction in each bucket, and adjust the recurrence and other offsets
464   // accordingly.
465   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
466     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
467       if (II->getIntrinsicID() == Intrinsic::prefetch)
468         continue;
469 
470     // If we'd otherwise pick the first element anyway, there's nothing to do.
471     if (j == 0)
472       break;
473 
474     // If our chosen element has no offset from the base pointer, there's
475     // nothing to do.
476     if (!BucketChain.Elements[j].Offset ||
477         BucketChain.Elements[j].Offset->isZero())
478       break;
479 
480     const SCEV *Offset = BucketChain.Elements[j].Offset;
481     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
482     for (auto &E : BucketChain.Elements) {
483       if (E.Offset)
484         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
485       else
486         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
487     }
488 
489     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
490     break;
491   }
492   return true;
493 }
494 
495 bool PPCLoopInstrFormPrep::rewriteLoadStores(Loop *L, Bucket &BucketChain,
496                                           SmallSet<BasicBlock *, 16> &BBChanged,
497                                           InstrForm Form) {
498   bool MadeChange = false;
499   const SCEVAddRecExpr *BasePtrSCEV =
500       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
501   if (!BasePtrSCEV->isAffine())
502     return MadeChange;
503 
504   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
505 
506   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
507 
508   // The instruction corresponding to the Bucket's BaseSCEV must be the first
509   // in the vector of elements.
510   Instruction *MemI = BucketChain.Elements.begin()->Instr;
511   Value *BasePtr = GetPointerOperand(MemI);
512   assert(BasePtr && "No pointer operand");
513 
514   Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
515   Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
516     BasePtr->getType()->getPointerAddressSpace());
517 
518   if (!SE->isLoopInvariant(BasePtrSCEV->getStart(), L))
519     return MadeChange;
520 
521   const SCEVConstant *BasePtrIncSCEV =
522     dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
523   if (!BasePtrIncSCEV)
524     return MadeChange;
525 
526   // For some DS form load/store instructions, it can also be an update form,
527   // if the stride is a multipler of 4. Use update form if prefer it.
528   bool CanPreInc = (Form == UpdateForm ||
529                     ((Form == DSForm) && !BasePtrIncSCEV->getAPInt().urem(4) &&
530                      PreferUpdateForm));
531   const SCEV *BasePtrStartSCEV = nullptr;
532   if (CanPreInc)
533     BasePtrStartSCEV =
534         SE->getMinusSCEV(BasePtrSCEV->getStart(), BasePtrIncSCEV);
535   else
536     BasePtrStartSCEV = BasePtrSCEV->getStart();
537 
538   if (!isSafeToExpand(BasePtrStartSCEV, *SE))
539     return MadeChange;
540 
541   if (alreadyPrepared(L, MemI, BasePtrStartSCEV, BasePtrIncSCEV, Form))
542     return MadeChange;
543 
544   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
545 
546   BasicBlock *Header = L->getHeader();
547   unsigned HeaderLoopPredCount = pred_size(Header);
548   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
549 
550   PHINode *NewPHI =
551       PHINode::Create(I8PtrTy, HeaderLoopPredCount,
552                       getInstrName(MemI, PHINodeNameSuffix),
553                       Header->getFirstNonPHI());
554 
555   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
556   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
557                                             LoopPredecessor->getTerminator());
558 
559   // Note that LoopPredecessor might occur in the predecessor list multiple
560   // times, and we need to add it the right number of times.
561   for (auto PI : predecessors(Header)) {
562     if (PI != LoopPredecessor)
563       continue;
564 
565     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
566   }
567 
568   Instruction *PtrInc = nullptr;
569   Instruction *NewBasePtr = nullptr;
570   if (CanPreInc) {
571     Instruction *InsPoint = &*Header->getFirstInsertionPt();
572     PtrInc = GetElementPtrInst::Create(
573         I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
574         getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
575     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
576     for (auto PI : predecessors(Header)) {
577       if (PI == LoopPredecessor)
578         continue;
579 
580       NewPHI->addIncoming(PtrInc, PI);
581     }
582     if (PtrInc->getType() != BasePtr->getType())
583       NewBasePtr = new BitCastInst(
584           PtrInc, BasePtr->getType(),
585           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
586     else
587       NewBasePtr = PtrInc;
588   } else {
589     // Note that LoopPredecessor might occur in the predecessor list multiple
590     // times, and we need to make sure no more incoming value for them in PHI.
591     for (auto PI : predecessors(Header)) {
592       if (PI == LoopPredecessor)
593         continue;
594 
595       // For the latch predecessor, we need to insert a GEP just before the
596       // terminator to increase the address.
597       BasicBlock *BB = PI;
598       Instruction *InsPoint = BB->getTerminator();
599       PtrInc = GetElementPtrInst::Create(
600           I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
601           getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
602 
603       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
604 
605       NewPHI->addIncoming(PtrInc, PI);
606     }
607     PtrInc = NewPHI;
608     if (NewPHI->getType() != BasePtr->getType())
609       NewBasePtr =
610           new BitCastInst(NewPHI, BasePtr->getType(),
611                           getInstrName(NewPHI, CastNodeNameSuffix),
612                           &*Header->getFirstInsertionPt());
613     else
614       NewBasePtr = NewPHI;
615   }
616 
617   // Clear the rewriter cache, because values that are in the rewriter's cache
618   // can be deleted below, causing the AssertingVH in the cache to trigger.
619   SCEVE.clear();
620 
621   if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
622     BBChanged.insert(IDel->getParent());
623   BasePtr->replaceAllUsesWith(NewBasePtr);
624   RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
625 
626   // Keep track of the replacement pointer values we've inserted so that we
627   // don't generate more pointer values than necessary.
628   SmallPtrSet<Value *, 16> NewPtrs;
629   NewPtrs.insert(NewBasePtr);
630 
631   for (auto I = std::next(BucketChain.Elements.begin()),
632        IE = BucketChain.Elements.end(); I != IE; ++I) {
633     Value *Ptr = GetPointerOperand(I->Instr);
634     assert(Ptr && "No pointer operand");
635     if (NewPtrs.count(Ptr))
636       continue;
637 
638     Instruction *RealNewPtr;
639     if (!I->Offset || I->Offset->getValue()->isZero()) {
640       RealNewPtr = NewBasePtr;
641     } else {
642       Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
643       if (PtrIP && isa<Instruction>(NewBasePtr) &&
644           cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
645         PtrIP = nullptr;
646       else if (PtrIP && isa<PHINode>(PtrIP))
647         PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
648       else if (!PtrIP)
649         PtrIP = I->Instr;
650 
651       GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
652           I8Ty, PtrInc, I->Offset->getValue(),
653           getInstrName(I->Instr, GEPNodeOffNameSuffix), PtrIP);
654       if (!PtrIP)
655         NewPtr->insertAfter(cast<Instruction>(PtrInc));
656       NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
657       RealNewPtr = NewPtr;
658     }
659 
660     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
661       BBChanged.insert(IDel->getParent());
662 
663     Instruction *ReplNewPtr;
664     if (Ptr->getType() != RealNewPtr->getType()) {
665       ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
666         getInstrName(Ptr, CastNodeNameSuffix));
667       ReplNewPtr->insertAfter(RealNewPtr);
668     } else
669       ReplNewPtr = RealNewPtr;
670 
671     Ptr->replaceAllUsesWith(ReplNewPtr);
672     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
673 
674     NewPtrs.insert(RealNewPtr);
675   }
676 
677   MadeChange = true;
678 
679   SuccPrepCount++;
680 
681   if (Form == DSForm && !CanPreInc)
682     DSFormChainRewritten++;
683   else if (Form == DQForm)
684     DQFormChainRewritten++;
685   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
686     UpdFormChainRewritten++;
687 
688   return MadeChange;
689 }
690 
691 bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
692                                        SmallVector<Bucket, 16> &Buckets) {
693   bool MadeChange = false;
694   if (Buckets.empty())
695     return MadeChange;
696   SmallSet<BasicBlock *, 16> BBChanged;
697   for (auto &Bucket : Buckets)
698     // The base address of each bucket is transformed into a phi and the others
699     // are rewritten based on new base.
700     if (prepareBaseForUpdateFormChain(Bucket))
701       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
702 
703   if (MadeChange)
704     for (auto &BB : L->blocks())
705       if (BBChanged.count(BB))
706         DeleteDeadPHIs(BB);
707   return MadeChange;
708 }
709 
710 bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
711                                      InstrForm Form) {
712   bool MadeChange = false;
713 
714   if (Buckets.empty())
715     return MadeChange;
716 
717   SmallSet<BasicBlock *, 16> BBChanged;
718   for (auto &Bucket : Buckets) {
719     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
720       continue;
721     if (prepareBaseForDispFormChain(Bucket, Form))
722       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
723   }
724 
725   if (MadeChange)
726     for (auto &BB : L->blocks())
727       if (BBChanged.count(BB))
728         DeleteDeadPHIs(BB);
729   return MadeChange;
730 }
731 
732 // In order to prepare for the preferred instruction form, a PHI is added.
733 // This function will check to see if that PHI already exists and will return
734 // true if it found an existing PHI with the matched start and increment as the
735 // one we wanted to create.
736 bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction* MemI,
737                                         const SCEV *BasePtrStartSCEV,
738                                         const SCEVConstant *BasePtrIncSCEV,
739                                         InstrForm Form) {
740   BasicBlock *BB = MemI->getParent();
741   if (!BB)
742     return false;
743 
744   BasicBlock *PredBB = L->getLoopPredecessor();
745   BasicBlock *LatchBB = L->getLoopLatch();
746 
747   if (!PredBB || !LatchBB)
748     return false;
749 
750   // Run through the PHIs and see if we have some that looks like a preparation
751   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
752   for (auto & CurrentPHI : PHIIter) {
753     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
754     if (!CurrentPHINode)
755       continue;
756 
757     if (!SE->isSCEVable(CurrentPHINode->getType()))
758       continue;
759 
760     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
761 
762     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
763     if (!PHIBasePtrSCEV)
764       continue;
765 
766     const SCEVConstant *PHIBasePtrIncSCEV =
767       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
768     if (!PHIBasePtrIncSCEV)
769       continue;
770 
771     if (CurrentPHINode->getNumIncomingValues() == 2) {
772       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
773            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
774           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
775            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
776         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
777           // The existing PHI (CurrentPHINode) has the same start and increment
778           // as the PHI that we wanted to create.
779           if (Form == UpdateForm &&
780               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
781             ++PHINodeAlreadyExistsUpdate;
782             return true;
783           }
784           if (Form == DSForm || Form == DQForm) {
785             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
786                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
787             if (Diff && !Diff->getAPInt().urem(Form)) {
788               if (Form == DSForm)
789                 ++PHINodeAlreadyExistsDS;
790               else
791                 ++PHINodeAlreadyExistsDQ;
792               return true;
793             }
794           }
795         }
796       }
797     }
798   }
799   return false;
800 }
801 
802 bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
803   bool MadeChange = false;
804 
805   // Only prep. the inner-most loop
806   if (!L->isInnermost())
807     return MadeChange;
808 
809   // Return if already done enough preparation.
810   if (SuccPrepCount >= MaxVarsPrep)
811     return MadeChange;
812 
813   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
814 
815   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
816   // If there is no loop predecessor, or the loop predecessor's terminator
817   // returns a value (which might contribute to determining the loop's
818   // iteration space), insert a new preheader for the loop.
819   if (!LoopPredecessor ||
820       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
821     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
822     if (LoopPredecessor)
823       MadeChange = true;
824   }
825   if (!LoopPredecessor) {
826     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
827     return MadeChange;
828   }
829   // Check if a load/store has update form. This lambda is used by function
830   // collectCandidates which can collect candidates for types defined by lambda.
831   auto isUpdateFormCandidate = [&] (const Instruction *I,
832                                     const Value *PtrValue) {
833     assert((PtrValue && I) && "Invalid parameter!");
834     // There are no update forms for Altivec vector load/stores.
835     if (ST && ST->hasAltivec() &&
836         PtrValue->getType()->getPointerElementType()->isVectorTy())
837       return false;
838     // There are no update forms for P10 lxvp/stxvp intrinsic.
839     auto *II = dyn_cast<IntrinsicInst>(I);
840     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_mma_lxvp) ||
841                II->getIntrinsicID() == Intrinsic::ppc_mma_stxvp))
842       return false;
843     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
844     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
845     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
846     // useless and possible to break some original well-form addressing mode
847     // to make this pre-inc prep for it.
848     if (PtrValue->getType()->getPointerElementType()->isIntegerTy(64)) {
849       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
850       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
851       if (!LARSCEV || LARSCEV->getLoop() != L)
852         return false;
853       if (const SCEVConstant *StepConst =
854               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
855         const APInt &ConstInt = StepConst->getValue()->getValue();
856         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
857           return false;
858       }
859     }
860     return true;
861   };
862 
863   // Check if a load/store has DS form.
864   auto isDSFormCandidate = [] (const Instruction *I, const Value *PtrValue) {
865     assert((PtrValue && I) && "Invalid parameter!");
866     if (isa<IntrinsicInst>(I))
867       return false;
868     Type *PointerElementType = PtrValue->getType()->getPointerElementType();
869     return (PointerElementType->isIntegerTy(64)) ||
870            (PointerElementType->isFloatTy()) ||
871            (PointerElementType->isDoubleTy()) ||
872            (PointerElementType->isIntegerTy(32) &&
873             llvm::any_of(I->users(),
874                          [](const User *U) { return isa<SExtInst>(U); }));
875   };
876 
877   // Check if a load/store has DQ form.
878   auto isDQFormCandidate = [&] (const Instruction *I, const Value *PtrValue) {
879     assert((PtrValue && I) && "Invalid parameter!");
880     // Check if it is a P10 lxvp/stxvp intrinsic.
881     auto *II = dyn_cast<IntrinsicInst>(I);
882     if (II)
883       return II->getIntrinsicID() == Intrinsic::ppc_mma_lxvp ||
884              II->getIntrinsicID() == Intrinsic::ppc_mma_stxvp;
885     // Check if it is a P9 vector load/store.
886     return ST && ST->hasP9Vector() &&
887            (PtrValue->getType()->getPointerElementType()->isVectorTy());
888   };
889 
890   // intrinsic for update form.
891   SmallVector<Bucket, 16> UpdateFormBuckets =
892       collectCandidates(L, isUpdateFormCandidate, MaxVarsUpdateForm);
893 
894   // Prepare for update form.
895   if (!UpdateFormBuckets.empty())
896     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
897 
898   // Collect buckets of comparable addresses used by loads and stores for DS
899   // form.
900   SmallVector<Bucket, 16> DSFormBuckets =
901       collectCandidates(L, isDSFormCandidate, MaxVarsDSForm);
902 
903   // Prepare for DS form.
904   if (!DSFormBuckets.empty())
905     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
906 
907   // Collect buckets of comparable addresses used by loads and stores for DQ
908   // form.
909   SmallVector<Bucket, 16> DQFormBuckets =
910       collectCandidates(L, isDQFormCandidate, MaxVarsDQForm);
911 
912   // Prepare for DQ form.
913   if (!DQFormBuckets.empty())
914     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
915 
916   return MadeChange;
917 }
918