xref: /llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision f6db18fd4ac83468cfbea512c4a2723bc98d830c)
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 // 3: common multiple chains for the load/stores with same offsets in the loop,
44 //    so that we can reuse the offsets and reduce the register pressure in the
45 //    loop. This transformation can also increase the loop ILP as now each chain
46 //    uses its own loop induction add/addi. But this will increase the number of
47 //    add/addi in the loop.
48 //
49 //    Generically, this means transforming loops like this:
50 //
51 //    char *p;
52 //    A1 = p + base1
53 //    A2 = p + base1 + offset
54 //    B1 = p + base2
55 //    B2 = p + base2 + offset
56 //
57 //    for (int i = 0; i < n; i++)
58 //      unsigned long x1 = *(unsigned long *)(A1 + i);
59 //      unsigned long x2 = *(unsigned long *)(A2 + i)
60 //      unsigned long x3 = *(unsigned long *)(B1 + i);
61 //      unsigned long x4 = *(unsigned long *)(B2 + i);
62 //    }
63 //
64 //    to look like this:
65 //
66 //    A1_new = p + base1 // chain 1
67 //    B1_new = p + base2 // chain 2, now inside the loop, common offset is
68 //                       // reused.
69 //
70 //    for (long long i = 0; i < n; i+=count) {
71 //      unsigned long x1 = *(unsigned long *)(A1_new + i);
72 //      unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
73 //      unsigned long x3 = *(unsigned long *)(B1_new + i);
74 //      unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
75 //    }
76 //===----------------------------------------------------------------------===//
77 
78 #include "PPC.h"
79 #include "PPCSubtarget.h"
80 #include "PPCTargetMachine.h"
81 #include "llvm/ADT/DepthFirstIterator.h"
82 #include "llvm/ADT/SmallPtrSet.h"
83 #include "llvm/ADT/SmallSet.h"
84 #include "llvm/ADT/SmallVector.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/Analysis/LoopInfo.h"
87 #include "llvm/Analysis/ScalarEvolution.h"
88 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
89 #include "llvm/IR/BasicBlock.h"
90 #include "llvm/IR/CFG.h"
91 #include "llvm/IR/Dominators.h"
92 #include "llvm/IR/Instruction.h"
93 #include "llvm/IR/Instructions.h"
94 #include "llvm/IR/IntrinsicInst.h"
95 #include "llvm/IR/IntrinsicsPowerPC.h"
96 #include "llvm/IR/Module.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/InitializePasses.h"
100 #include "llvm/Pass.h"
101 #include "llvm/Support/Casting.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Transforms/Scalar.h"
105 #include "llvm/Transforms/Utils.h"
106 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
107 #include "llvm/Transforms/Utils/Local.h"
108 #include "llvm/Transforms/Utils/LoopUtils.h"
109 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
110 #include <cassert>
111 #include <iterator>
112 #include <utility>
113 
114 #define DEBUG_TYPE "ppc-loop-instr-form-prep"
115 
116 using namespace llvm;
117 
118 static cl::opt<unsigned>
119     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
120                 cl::ZeroOrMore,
121                 cl::desc("Potential common base number threshold per function "
122                          "for PPC loop prep"));
123 
124 static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
125                                  cl::init(true), cl::Hidden,
126   cl::desc("prefer update form when ds form is also a update form"));
127 
128 static cl::opt<bool> EnableChainCommoning(
129     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
130     cl::desc("Enable chain commoning in PPC loop prepare pass."));
131 
132 // Sum of following 3 per loop thresholds for all loops can not be larger
133 // than MaxVarsPrep.
134 // now the thresholds for each kind prep are exterimental values on Power9.
135 static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
136                                  cl::Hidden, cl::init(3),
137   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
138            "form"));
139 
140 static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
141                                  cl::Hidden, cl::init(3),
142   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
143 
144 static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
145                                  cl::Hidden, cl::init(8),
146   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
147 
148 // Commoning chain will reduce the register pressure, so we don't consider about
149 // the PHI nodes number.
150 // But commoning chain will increase the addi/add number in the loop and also
151 // increase loop ILP. Maximum chain number should be same with hardware
152 // IssueWidth, because we won't benefit from ILP if the parallel chains number
153 // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
154 // there would be 4 buckets at most on P9(IssueWidth is 8).
155 static cl::opt<unsigned> MaxVarsChainCommon(
156     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
157     cl::desc("Bucket number per loop for PPC loop chain common"));
158 
159 // If would not be profitable if the common base has only one load/store, ISEL
160 // should already be able to choose best load/store form based on offset for
161 // single load/store. Set minimal profitable value default to 2 and make it as
162 // an option.
163 static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
164                                     cl::Hidden, cl::init(2),
165   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
166            "preparation"));
167 
168 static cl::opt<unsigned> ChainCommonPrepMinThreshold(
169     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
170     cl::desc("Minimal common base load/store instructions triggering chain "
171              "commoning preparation. Must be not smaller than 4"));
172 
173 STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
174 STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
175 STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
176 STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
177 STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
178 STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
179 STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
180 
181 namespace {
182   struct BucketElement {
183     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
184     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
185 
186     const SCEV *Offset;
187     Instruction *Instr;
188   };
189 
190   struct Bucket {
191     Bucket(const SCEV *B, Instruction *I)
192         : BaseSCEV(B), Elements(1, BucketElement(I)) {
193       ChainSize = 0;
194     }
195 
196     // The base of the whole bucket.
197     const SCEV *BaseSCEV;
198 
199     // All elements in the bucket. In the bucket, the element with the BaseSCEV
200     // has no offset and all other elements are stored as offsets to the
201     // BaseSCEV.
202     SmallVector<BucketElement, 16> Elements;
203 
204     // The potential chains size. This is used for chain commoning only.
205     unsigned ChainSize;
206 
207     // The base for each potential chain. This is used for chain commoning only.
208     SmallVector<BucketElement, 16> ChainBases;
209   };
210 
211   // "UpdateForm" is not a real PPC instruction form, it stands for dform
212   // load/store with update like ldu/stdu, or Prefetch intrinsic.
213   // For DS form instructions, their displacements must be multiple of 4.
214   // For DQ form instructions, their displacements must be multiple of 16.
215   enum InstrForm { UpdateForm = 1, DSForm = 4, DQForm = 16 };
216 
217   class PPCLoopInstrFormPrep : public FunctionPass {
218   public:
219     static char ID; // Pass ID, replacement for typeid
220 
221     PPCLoopInstrFormPrep() : FunctionPass(ID) {
222       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
223     }
224 
225     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
226       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
227     }
228 
229     void getAnalysisUsage(AnalysisUsage &AU) const override {
230       AU.addPreserved<DominatorTreeWrapperPass>();
231       AU.addRequired<LoopInfoWrapperPass>();
232       AU.addPreserved<LoopInfoWrapperPass>();
233       AU.addRequired<ScalarEvolutionWrapperPass>();
234     }
235 
236     bool runOnFunction(Function &F) override;
237 
238   private:
239     PPCTargetMachine *TM = nullptr;
240     const PPCSubtarget *ST;
241     DominatorTree *DT;
242     LoopInfo *LI;
243     ScalarEvolution *SE;
244     bool PreserveLCSSA;
245     bool HasCandidateForPrepare;
246 
247     /// Successful preparation number for Update/DS/DQ form in all inner most
248     /// loops. One successful preparation will put one common base out of loop,
249     /// this may leads to register presure like LICM does.
250     /// Make sure total preparation number can be controlled by option.
251     unsigned SuccPrepCount;
252 
253     bool runOnLoop(Loop *L);
254 
255     /// Check if required PHI node is already exist in Loop \p L.
256     bool alreadyPrepared(Loop *L, Instruction *MemI,
257                          const SCEV *BasePtrStartSCEV,
258                          const SCEV *BasePtrIncSCEV, InstrForm Form);
259 
260     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
261     Value *getNodeForInc(Loop *L, Instruction *MemI,
262                          const SCEV *BasePtrIncSCEV);
263 
264     /// Common chains to reuse offsets for a loop to reduce register pressure.
265     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
266 
267     /// Find out the potential commoning chains and their bases.
268     bool prepareBasesForCommoningChains(Bucket &BucketChain);
269 
270     /// Rewrite load/store according to the common chains.
271     bool
272     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
273                                         SmallSet<BasicBlock *, 16> &BBChanged);
274 
275     /// Collect condition matched(\p isValidCandidate() returns true)
276     /// candidates in Loop \p L.
277     SmallVector<Bucket, 16> collectCandidates(
278         Loop *L,
279         std::function<bool(const Instruction *, Value *, const Type *)>
280             isValidCandidate,
281         std::function<bool(const SCEV *)> isValidDiff,
282         unsigned MaxCandidateNum);
283 
284     /// Add a candidate to candidates \p Buckets if diff between candidate and
285     /// one base in \p Buckets matches \p isValidDiff.
286     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
287                          SmallVector<Bucket, 16> &Buckets,
288                          std::function<bool(const SCEV *)> isValidDiff,
289                          unsigned MaxCandidateNum);
290 
291     /// Prepare all candidates in \p Buckets for update form.
292     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
293 
294     /// Prepare all candidates in \p Buckets for displacement form, now for
295     /// ds/dq.
296     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
297                       InstrForm Form);
298 
299     /// Prepare for one chain \p BucketChain, find the best base element and
300     /// update all other elements in \p BucketChain accordingly.
301     /// \p Form is used to find the best base element.
302     /// If success, best base element must be stored as the first element of
303     /// \p BucketChain.
304     /// Return false if no base element found, otherwise return true.
305     bool prepareBaseForDispFormChain(Bucket &BucketChain,
306                                      InstrForm Form);
307 
308     /// Prepare for one chain \p BucketChain, find the best base element and
309     /// update all other elements in \p BucketChain accordingly.
310     /// If success, best base element must be stored as the first element of
311     /// \p BucketChain.
312     /// Return false if no base element found, otherwise return true.
313     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
314 
315     /// Rewrite load/store instructions in \p BucketChain according to
316     /// preparation.
317     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
318                            SmallSet<BasicBlock *, 16> &BBChanged,
319                            InstrForm Form);
320 
321     /// Rewrite for the base load/store of a chain.
322     std::pair<Instruction *, Instruction *>
323     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
324                    Instruction *BaseMemI, bool CanPreInc, InstrForm Form,
325                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
326 
327     /// Rewrite for the other load/stores of a chain according to the new \p
328     /// Base.
329     Instruction *
330     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
331                             const BucketElement &Element, Value *OffToBase,
332                             SmallPtrSet<Value *, 16> &DeletedPtrs);
333   };
334 
335 } // end anonymous namespace
336 
337 char PPCLoopInstrFormPrep::ID = 0;
338 static const char *name = "Prepare loop for ppc preferred instruction forms";
339 INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
340 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
341 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
342 INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
343 
344 static constexpr StringRef PHINodeNameSuffix    = ".phi";
345 static constexpr StringRef CastNodeNameSuffix   = ".cast";
346 static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
347 static constexpr StringRef GEPNodeOffNameSuffix = ".off";
348 
349 FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
350   return new PPCLoopInstrFormPrep(TM);
351 }
352 
353 static bool IsPtrInBounds(Value *BasePtr) {
354   Value *StrippedBasePtr = BasePtr;
355   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
356     StrippedBasePtr = BC->getOperand(0);
357   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
358     return GEP->isInBounds();
359 
360   return false;
361 }
362 
363 static std::string getInstrName(const Value *I, StringRef Suffix) {
364   assert(I && "Invalid paramater!");
365   if (I->hasName())
366     return (I->getName() + Suffix).str();
367   else
368     return "";
369 }
370 
371 static Value *getPointerOperandAndType(Value *MemI,
372                                        Type **PtrElementType = nullptr) {
373 
374   Value *PtrValue = nullptr;
375   Type *PointerElementType = nullptr;
376 
377   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
378     PtrValue = LMemI->getPointerOperand();
379     PointerElementType = LMemI->getType();
380   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
381     PtrValue = SMemI->getPointerOperand();
382     PointerElementType = SMemI->getValueOperand()->getType();
383   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
384     PointerElementType = Type::getInt8Ty(MemI->getContext());
385     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
386         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
387       PtrValue = IMemI->getArgOperand(0);
388     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
389       PtrValue = IMemI->getArgOperand(1);
390     }
391   }
392   /*Get ElementType if PtrElementType is not null.*/
393   if (PtrElementType)
394     *PtrElementType = PointerElementType;
395 
396   return PtrValue;
397 }
398 
399 bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
400   if (skipFunction(F))
401     return false;
402 
403   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
404   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
405   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
406   DT = DTWP ? &DTWP->getDomTree() : nullptr;
407   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
408   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
409   SuccPrepCount = 0;
410 
411   bool MadeChange = false;
412 
413   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
414     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
415       MadeChange |= runOnLoop(*L);
416 
417   return MadeChange;
418 }
419 
420 // Finding the minimal(chain_number + reusable_offset_number) is a complicated
421 // algorithmic problem.
422 // For now, the algorithm used here is simply adjusted to handle the case for
423 // manually unrolling cases.
424 // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
425 // reusable_offset_number for one base with multiple offsets.
426 bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
427   // The minimal size for profitable chain commoning:
428   // A1 = base + offset1
429   // A2 = base + offset2 (offset2 - offset1 = X)
430   // A3 = base + offset3
431   // A4 = base + offset4 (offset4 - offset3 = X)
432   // ======>
433   // base1 = base + offset1
434   // base2 = base + offset3
435   // A1 = base1
436   // A2 = base1 + X
437   // A3 = base2
438   // A4 = base2 + X
439   //
440   // There is benefit because of reuse of offest 'X'.
441 
442   assert(ChainCommonPrepMinThreshold >= 4 &&
443          "Thredhold can not be smaller than 4!\n");
444   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
445     return false;
446 
447   // We simply select the FirstOffset as the first reusable offset between each
448   // chain element 1 and element 0.
449   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
450 
451   // Figure out how many times above FirstOffset is used in the chain.
452   // For a success commoning chain candidate, offset difference between each
453   // chain element 1 and element 0 must be also FirstOffset.
454   unsigned FirstOffsetReusedCount = 1;
455 
456   // Figure out how many times above FirstOffset is used in the first chain.
457   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
458   unsigned FirstOffsetReusedCountInFirstChain = 1;
459 
460   unsigned EleNum = CBucket.Elements.size();
461   bool SawChainSeparater = false;
462   for (unsigned j = 2; j != EleNum; ++j) {
463     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
464                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
465       if (!SawChainSeparater)
466         FirstOffsetReusedCountInFirstChain++;
467       FirstOffsetReusedCount++;
468     } else
469       // For now, if we meet any offset which is not FirstOffset, we assume we
470       // find a new Chain.
471       // This makes us miss some opportunities.
472       // For example, we can common:
473       //
474       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
475       //
476       // as two chains:
477       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
478       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
479       //
480       // But we fail to common:
481       //
482       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
483       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
484 
485       SawChainSeparater = true;
486   }
487 
488   // FirstOffset is not reused, skip this bucket.
489   if (FirstOffsetReusedCount == 1)
490     return false;
491 
492   unsigned ChainNum =
493       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
494 
495   // All elements are increased by FirstOffset.
496   // The number of chains should be sqrt(EleNum).
497   if (!SawChainSeparater)
498     ChainNum = (unsigned)sqrt((double)EleNum);
499 
500   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
501 
502   // If this is not a perfect chain(eg: not all elements can be put inside
503   // commoning chains.), skip now.
504   if (CBucket.ChainSize * ChainNum != EleNum)
505     return false;
506 
507   if (SawChainSeparater) {
508     // Check that the offset seqs are the same for all chains.
509     for (unsigned i = 1; i < CBucket.ChainSize; i++)
510       for (unsigned j = 1; j < ChainNum; j++)
511         if (CBucket.Elements[i].Offset !=
512             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
513                              CBucket.Elements[j * CBucket.ChainSize].Offset))
514           return false;
515   }
516 
517   for (unsigned i = 0; i < ChainNum; i++)
518     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
519 
520   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
521 
522   return true;
523 }
524 
525 bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
526                                           SmallVector<Bucket, 16> &Buckets) {
527   bool MadeChange = false;
528 
529   if (Buckets.empty())
530     return MadeChange;
531 
532   SmallSet<BasicBlock *, 16> BBChanged;
533 
534   for (auto &Bucket : Buckets) {
535     if (prepareBasesForCommoningChains(Bucket))
536       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
537   }
538 
539   if (MadeChange)
540     for (auto *BB : BBChanged)
541       DeleteDeadPHIs(BB);
542   return MadeChange;
543 }
544 
545 bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
546     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
547   bool MadeChange = false;
548 
549   assert(Bucket.Elements.size() ==
550              Bucket.ChainBases.size() * Bucket.ChainSize &&
551          "invalid bucket for chain commoning!\n");
552   SmallPtrSet<Value *, 16> DeletedPtrs;
553 
554   BasicBlock *Header = L->getHeader();
555   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
556 
557   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
558                      "loopprepare-chaincommon");
559 
560   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
561     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
562     const SCEV *BaseSCEV =
563         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
564                                   Bucket.Elements[BaseElemIdx].Offset)
565                  : Bucket.BaseSCEV;
566     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
567 
568     // Make sure the base is able to expand.
569     if (!isSafeToExpand(BasePtrSCEV->getStart(), *SE))
570       return MadeChange;
571 
572     assert(BasePtrSCEV->isAffine() &&
573            "Invalid SCEV type for the base ptr for a candidate chain!\n");
574 
575     std::pair<Instruction *, Instruction *> Base =
576         rewriteForBase(L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
577                        false /* CanPreInc */, UpdateForm, SCEVE, DeletedPtrs);
578 
579     if (!Base.first || !Base.second)
580       return MadeChange;
581 
582     // Keep track of the replacement pointer values we've inserted so that we
583     // don't generate more pointer values than necessary.
584     SmallPtrSet<Value *, 16> NewPtrs;
585     NewPtrs.insert(Base.first);
586 
587     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
588          ++Idx) {
589       BucketElement &I = Bucket.Elements[Idx];
590       Value *Ptr = getPointerOperandAndType(I.Instr);
591       assert(Ptr && "No pointer operand");
592       if (NewPtrs.count(Ptr))
593         continue;
594 
595       const SCEV *OffsetSCEV =
596           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
597                                          Bucket.Elements[BaseElemIdx].Offset)
598                       : Bucket.Elements[Idx].Offset;
599 
600       // Make sure offset is able to expand. Only need to check one time as the
601       // offsets are reused between different chains.
602       if (!BaseElemIdx)
603         if (!isSafeToExpand(OffsetSCEV, *SE))
604           return false;
605 
606       Value *OffsetValue = SCEVE.expandCodeFor(
607           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
608 
609       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
610                                                     OffsetValue, DeletedPtrs);
611 
612       assert(NewPtr && "Wrong rewrite!\n");
613       NewPtrs.insert(NewPtr);
614     }
615 
616     ++ChainCommoningRewritten;
617   }
618 
619   // Clear the rewriter cache, because values that are in the rewriter's cache
620   // can be deleted below, causing the AssertingVH in the cache to trigger.
621   SCEVE.clear();
622 
623   for (auto *Ptr : DeletedPtrs) {
624     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
625       BBChanged.insert(IDel->getParent());
626     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
627   }
628 
629   MadeChange = true;
630   return MadeChange;
631 }
632 
633 // Rewrite the new base according to BasePtrSCEV.
634 // bb.loop.preheader:
635 //   %newstart = ...
636 // bb.loop.body:
637 //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
638 //   ...
639 //   %add = getelementptr %phinode, %inc
640 //
641 // First returned instruciton is %phinode (or a type cast to %phinode), caller
642 // needs this value to rewrite other load/stores in the same chain.
643 // Second returned instruction is %add, caller needs this value to rewrite other
644 // load/stores in the same chain.
645 std::pair<Instruction *, Instruction *>
646 PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
647                                      Instruction *BaseMemI, bool CanPreInc,
648                                      InstrForm Form, SCEVExpander &SCEVE,
649                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
650 
651   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
652 
653   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
654 
655   Value *BasePtr = getPointerOperandAndType(BaseMemI);
656   assert(BasePtr && "No pointer operand");
657 
658   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
659   Type *I8PtrTy =
660       Type::getInt8PtrTy(BaseMemI->getParent()->getContext(),
661                          BasePtr->getType()->getPointerAddressSpace());
662 
663   bool IsConstantInc = false;
664   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
665   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
666 
667   const SCEVConstant *BasePtrIncConstantSCEV =
668       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
669   if (BasePtrIncConstantSCEV)
670     IsConstantInc = true;
671 
672   // No valid representation for the increment.
673   if (!IncNode) {
674     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
675     return std::make_pair(nullptr, nullptr);
676   }
677 
678   const SCEV *BasePtrStartSCEV = nullptr;
679   if (CanPreInc) {
680     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
681            "Increment is not loop invariant!\n");
682     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
683                                         IsConstantInc ? BasePtrIncConstantSCEV
684                                                       : BasePtrIncSCEV);
685   } else
686     BasePtrStartSCEV = BasePtrSCEV->getStart();
687 
688   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
689     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
690     return std::make_pair(nullptr, nullptr);
691   }
692 
693   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
694 
695   BasicBlock *Header = L->getHeader();
696   unsigned HeaderLoopPredCount = pred_size(Header);
697   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
698 
699   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
700                                     getInstrName(BaseMemI, PHINodeNameSuffix),
701                                     Header->getFirstNonPHI());
702 
703   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
704                                             LoopPredecessor->getTerminator());
705 
706   // Note that LoopPredecessor might occur in the predecessor list multiple
707   // times, and we need to add it the right number of times.
708   for (auto PI : predecessors(Header)) {
709     if (PI != LoopPredecessor)
710       continue;
711 
712     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
713   }
714 
715   Instruction *PtrInc = nullptr;
716   Instruction *NewBasePtr = nullptr;
717   if (CanPreInc) {
718     Instruction *InsPoint = &*Header->getFirstInsertionPt();
719     PtrInc = GetElementPtrInst::Create(
720         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
721         InsPoint);
722     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
723     for (auto PI : predecessors(Header)) {
724       if (PI == LoopPredecessor)
725         continue;
726 
727       NewPHI->addIncoming(PtrInc, PI);
728     }
729     if (PtrInc->getType() != BasePtr->getType())
730       NewBasePtr =
731           new BitCastInst(PtrInc, BasePtr->getType(),
732                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
733     else
734       NewBasePtr = PtrInc;
735   } else {
736     // Note that LoopPredecessor might occur in the predecessor list multiple
737     // times, and we need to make sure no more incoming value for them in PHI.
738     for (auto PI : predecessors(Header)) {
739       if (PI == LoopPredecessor)
740         continue;
741 
742       // For the latch predecessor, we need to insert a GEP just before the
743       // terminator to increase the address.
744       BasicBlock *BB = PI;
745       Instruction *InsPoint = BB->getTerminator();
746       PtrInc = GetElementPtrInst::Create(
747           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
748           InsPoint);
749       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
750 
751       NewPHI->addIncoming(PtrInc, PI);
752     }
753     PtrInc = NewPHI;
754     if (NewPHI->getType() != BasePtr->getType())
755       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
756                                    getInstrName(NewPHI, CastNodeNameSuffix),
757                                    &*Header->getFirstInsertionPt());
758     else
759       NewBasePtr = NewPHI;
760   }
761 
762   BasePtr->replaceAllUsesWith(NewBasePtr);
763 
764   DeletedPtrs.insert(BasePtr);
765 
766   return std::make_pair(NewBasePtr, PtrInc);
767 }
768 
769 Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
770     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
771     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
772   Instruction *NewBasePtr = Base.first;
773   Instruction *PtrInc = Base.second;
774   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
775 
776   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
777 
778   Value *Ptr = getPointerOperandAndType(Element.Instr);
779   assert(Ptr && "No pointer operand");
780 
781   Instruction *RealNewPtr;
782   if (!Element.Offset ||
783       (isa<SCEVConstant>(Element.Offset) &&
784        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
785     RealNewPtr = NewBasePtr;
786   } else {
787     Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
788     if (PtrIP && isa<Instruction>(NewBasePtr) &&
789         cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
790       PtrIP = nullptr;
791     else if (PtrIP && isa<PHINode>(PtrIP))
792       PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
793     else if (!PtrIP)
794       PtrIP = Element.Instr;
795 
796     assert(OffToBase && "There should be an offset for non base element!\n");
797     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
798         I8Ty, PtrInc, OffToBase,
799         getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
800     if (!PtrIP)
801       NewPtr->insertAfter(cast<Instruction>(PtrInc));
802     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
803     RealNewPtr = NewPtr;
804   }
805 
806   Instruction *ReplNewPtr;
807   if (Ptr->getType() != RealNewPtr->getType()) {
808     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
809                                  getInstrName(Ptr, CastNodeNameSuffix));
810     ReplNewPtr->insertAfter(RealNewPtr);
811   } else
812     ReplNewPtr = RealNewPtr;
813 
814   Ptr->replaceAllUsesWith(ReplNewPtr);
815   DeletedPtrs.insert(Ptr);
816 
817   return ReplNewPtr;
818 }
819 
820 void PPCLoopInstrFormPrep::addOneCandidate(
821     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
822     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
823   assert((MemI && getPointerOperandAndType(MemI)) &&
824          "Candidate should be a memory instruction.");
825   assert(LSCEV && "Invalid SCEV for Ptr value.");
826 
827   bool FoundBucket = false;
828   for (auto &B : Buckets) {
829     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
830         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
831       continue;
832     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
833     if (isValidDiff(Diff)) {
834       B.Elements.push_back(BucketElement(Diff, MemI));
835       FoundBucket = true;
836       break;
837     }
838   }
839 
840   if (!FoundBucket) {
841     if (Buckets.size() == MaxCandidateNum) {
842       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
843                         << MaxCandidateNum << "\n");
844       return;
845     }
846     Buckets.push_back(Bucket(LSCEV, MemI));
847   }
848 }
849 
850 SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
851     Loop *L,
852     std::function<bool(const Instruction *, Value *, const Type *)>
853         isValidCandidate,
854     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
855   SmallVector<Bucket, 16> Buckets;
856 
857   for (const auto &BB : L->blocks())
858     for (auto &J : *BB) {
859       Value *PtrValue = nullptr;
860       Type *PointerElementType = nullptr;
861       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
862 
863       if (!PtrValue)
864         continue;
865 
866       if (PtrValue->getType()->getPointerAddressSpace())
867         continue;
868 
869       if (L->isLoopInvariant(PtrValue))
870         continue;
871 
872       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
873       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
874       if (!LARSCEV || LARSCEV->getLoop() != L)
875         continue;
876 
877       // Mark that we have candidates for preparing.
878       HasCandidateForPrepare = true;
879 
880       if (isValidCandidate(&J, PtrValue, PointerElementType))
881         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
882     }
883   return Buckets;
884 }
885 
886 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
887                                                     InstrForm Form) {
888   // RemainderOffsetInfo details:
889   // key:            value of (Offset urem DispConstraint). For DSForm, it can
890   //                 be [0, 4).
891   // first of pair:  the index of first BucketElement whose remainder is equal
892   //                 to key. For key 0, this value must be 0.
893   // second of pair: number of load/stores with the same remainder.
894   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
895 
896   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
897     if (!BucketChain.Elements[j].Offset)
898       RemainderOffsetInfo[0] = std::make_pair(0, 1);
899     else {
900       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
901                                ->getAPInt()
902                                .urem(Form);
903       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
904         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
905       else
906         RemainderOffsetInfo[Remainder].second++;
907     }
908   }
909   // Currently we choose the most profitable base as the one which has the max
910   // number of load/store with same remainder.
911   // FIXME: adjust the base selection strategy according to load/store offset
912   // distribution.
913   // For example, if we have one candidate chain for DS form preparation, which
914   // contains following load/stores with different remainders:
915   // 1: 10 load/store whose remainder is 1;
916   // 2: 9 load/store whose remainder is 2;
917   // 3: 1 for remainder 3 and 0 for remainder 0;
918   // Now we will choose the first load/store whose remainder is 1 as base and
919   // adjust all other load/stores according to new base, so we will get 10 DS
920   // form and 10 X form.
921   // But we should be more clever, for this case we could use two bases, one for
922   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
923   // 1 X form.
924   unsigned MaxCountRemainder = 0;
925   for (unsigned j = 0; j < (unsigned)Form; j++)
926     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
927         RemainderOffsetInfo[j].second >
928             RemainderOffsetInfo[MaxCountRemainder].second)
929       MaxCountRemainder = j;
930 
931   // Abort when there are too few insts with common base.
932   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
933     return false;
934 
935   // If the first value is most profitable, no needed to adjust BucketChain
936   // elements as they are substracted the first value when collecting.
937   if (MaxCountRemainder == 0)
938     return true;
939 
940   // Adjust load/store to the new chosen base.
941   const SCEV *Offset =
942       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
943   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
944   for (auto &E : BucketChain.Elements) {
945     if (E.Offset)
946       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
947     else
948       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
949   }
950 
951   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
952             BucketChain.Elements[0]);
953   return true;
954 }
955 
956 // FIXME: implement a more clever base choosing policy.
957 // Currently we always choose an exist load/store offset. This maybe lead to
958 // suboptimal code sequences. For example, for one DS chain with offsets
959 // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
960 // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
961 // multipler of 4, it cannot be represented by sint16.
962 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
963   // We have a choice now of which instruction's memory operand we use as the
964   // base for the generated PHI. Always picking the first instruction in each
965   // bucket does not work well, specifically because that instruction might
966   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
967   // the choice is somewhat arbitrary, because the backend will happily
968   // generate direct offsets from both the pre-incremented and
969   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
970   // instruction in each bucket, and adjust the recurrence and other offsets
971   // accordingly.
972   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
973     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
974       if (II->getIntrinsicID() == Intrinsic::prefetch)
975         continue;
976 
977     // If we'd otherwise pick the first element anyway, there's nothing to do.
978     if (j == 0)
979       break;
980 
981     // If our chosen element has no offset from the base pointer, there's
982     // nothing to do.
983     if (!BucketChain.Elements[j].Offset ||
984         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
985       break;
986 
987     const SCEV *Offset = BucketChain.Elements[j].Offset;
988     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
989     for (auto &E : BucketChain.Elements) {
990       if (E.Offset)
991         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
992       else
993         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
994     }
995 
996     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
997     break;
998   }
999   return true;
1000 }
1001 
1002 bool PPCLoopInstrFormPrep::rewriteLoadStores(
1003     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1004     InstrForm Form) {
1005   bool MadeChange = false;
1006 
1007   const SCEVAddRecExpr *BasePtrSCEV =
1008       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
1009   if (!BasePtrSCEV->isAffine())
1010     return MadeChange;
1011 
1012   if (!isSafeToExpand(BasePtrSCEV->getStart(), *SE))
1013     return MadeChange;
1014 
1015   SmallPtrSet<Value *, 16> DeletedPtrs;
1016 
1017   BasicBlock *Header = L->getHeader();
1018   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
1019                      "loopprepare-formrewrite");
1020 
1021   // For some DS form load/store instructions, it can also be an update form,
1022   // if the stride is constant and is a multipler of 4. Use update form if
1023   // prefer it.
1024   bool CanPreInc = (Form == UpdateForm ||
1025                     ((Form == DSForm) &&
1026                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
1027                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
1028                           ->getAPInt()
1029                           .urem(4) &&
1030                      PreferUpdateForm));
1031 
1032   std::pair<Instruction *, Instruction *> Base =
1033       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
1034                      CanPreInc, Form, SCEVE, DeletedPtrs);
1035 
1036   if (!Base.first || !Base.second)
1037     return MadeChange;
1038 
1039   // Keep track of the replacement pointer values we've inserted so that we
1040   // don't generate more pointer values than necessary.
1041   SmallPtrSet<Value *, 16> NewPtrs;
1042   NewPtrs.insert(Base.first);
1043 
1044   for (auto I = std::next(BucketChain.Elements.begin()),
1045        IE = BucketChain.Elements.end(); I != IE; ++I) {
1046     Value *Ptr = getPointerOperandAndType(I->Instr);
1047     assert(Ptr && "No pointer operand");
1048     if (NewPtrs.count(Ptr))
1049       continue;
1050 
1051     Instruction *NewPtr = rewriteForBucketElement(
1052         Base, *I,
1053         I->Offset ? cast<SCEVConstant>(I->Offset)->getValue() : nullptr,
1054         DeletedPtrs);
1055     assert(NewPtr && "wrong rewrite!\n");
1056     NewPtrs.insert(NewPtr);
1057   }
1058 
1059   // Clear the rewriter cache, because values that are in the rewriter's cache
1060   // can be deleted below, causing the AssertingVH in the cache to trigger.
1061   SCEVE.clear();
1062 
1063   for (auto *Ptr : DeletedPtrs) {
1064     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
1065       BBChanged.insert(IDel->getParent());
1066     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
1067   }
1068 
1069   MadeChange = true;
1070 
1071   SuccPrepCount++;
1072 
1073   if (Form == DSForm && !CanPreInc)
1074     DSFormChainRewritten++;
1075   else if (Form == DQForm)
1076     DQFormChainRewritten++;
1077   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
1078     UpdFormChainRewritten++;
1079 
1080   return MadeChange;
1081 }
1082 
1083 bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
1084                                        SmallVector<Bucket, 16> &Buckets) {
1085   bool MadeChange = false;
1086   if (Buckets.empty())
1087     return MadeChange;
1088   SmallSet<BasicBlock *, 16> BBChanged;
1089   for (auto &Bucket : Buckets)
1090     // The base address of each bucket is transformed into a phi and the others
1091     // are rewritten based on new base.
1092     if (prepareBaseForUpdateFormChain(Bucket))
1093       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
1094 
1095   if (MadeChange)
1096     for (auto *BB : BBChanged)
1097       DeleteDeadPHIs(BB);
1098   return MadeChange;
1099 }
1100 
1101 bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
1102                                      InstrForm Form) {
1103   bool MadeChange = false;
1104 
1105   if (Buckets.empty())
1106     return MadeChange;
1107 
1108   SmallSet<BasicBlock *, 16> BBChanged;
1109   for (auto &Bucket : Buckets) {
1110     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
1111       continue;
1112     if (prepareBaseForDispFormChain(Bucket, Form))
1113       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
1114   }
1115 
1116   if (MadeChange)
1117     for (auto *BB : BBChanged)
1118       DeleteDeadPHIs(BB);
1119   return MadeChange;
1120 }
1121 
1122 // Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1123 // bb.loop.preheader:
1124 //   %start = ...
1125 // bb.loop.body:
1126 //   %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1127 //   ...
1128 //   %add = add %phinode, %inc  ; %inc is what we want to get.
1129 //
1130 Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1131                                            const SCEV *BasePtrIncSCEV) {
1132   // If the increment is a constant, no definition is needed.
1133   // Return the value directly.
1134   if (isa<SCEVConstant>(BasePtrIncSCEV))
1135     return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1136 
1137   if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1138     return nullptr;
1139 
1140   BasicBlock *BB = MemI->getParent();
1141   if (!BB)
1142     return nullptr;
1143 
1144   BasicBlock *LatchBB = L->getLoopLatch();
1145 
1146   if (!LatchBB)
1147     return nullptr;
1148 
1149   // Run through the PHIs and check their operands to find valid representation
1150   // for the increment SCEV.
1151   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1152   for (auto &CurrentPHI : PHIIter) {
1153     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1154     if (!CurrentPHINode)
1155       continue;
1156 
1157     if (!SE->isSCEVable(CurrentPHINode->getType()))
1158       continue;
1159 
1160     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1161 
1162     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1163     if (!PHIBasePtrSCEV)
1164       continue;
1165 
1166     const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1167 
1168     if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1169       continue;
1170 
1171     // Get the incoming value from the loop latch and check if the value has
1172     // the add form with the required increment.
1173     if (Instruction *I = dyn_cast<Instruction>(
1174             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1175       Value *StrippedBaseI = I;
1176       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1177         StrippedBaseI = BC->getOperand(0);
1178 
1179       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1180       if (!StrippedI)
1181         continue;
1182 
1183       // LSR pass may add a getelementptr instruction to do the loop increment,
1184       // also search in that getelementptr instruction.
1185       if (StrippedI->getOpcode() == Instruction::Add ||
1186           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1187            StrippedI->getNumOperands() == 2)) {
1188         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1189           return StrippedI->getOperand(0);
1190         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1191           return StrippedI->getOperand(1);
1192       }
1193     }
1194   }
1195   return nullptr;
1196 }
1197 
1198 // In order to prepare for the preferred instruction form, a PHI is added.
1199 // This function will check to see if that PHI already exists and will return
1200 // true if it found an existing PHI with the matched start and increment as the
1201 // one we wanted to create.
1202 bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1203                                            const SCEV *BasePtrStartSCEV,
1204                                            const SCEV *BasePtrIncSCEV,
1205                                            InstrForm Form) {
1206   BasicBlock *BB = MemI->getParent();
1207   if (!BB)
1208     return false;
1209 
1210   BasicBlock *PredBB = L->getLoopPredecessor();
1211   BasicBlock *LatchBB = L->getLoopLatch();
1212 
1213   if (!PredBB || !LatchBB)
1214     return false;
1215 
1216   // Run through the PHIs and see if we have some that looks like a preparation
1217   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1218   for (auto & CurrentPHI : PHIIter) {
1219     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1220     if (!CurrentPHINode)
1221       continue;
1222 
1223     if (!SE->isSCEVable(CurrentPHINode->getType()))
1224       continue;
1225 
1226     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1227 
1228     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1229     if (!PHIBasePtrSCEV)
1230       continue;
1231 
1232     const SCEVConstant *PHIBasePtrIncSCEV =
1233       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1234     if (!PHIBasePtrIncSCEV)
1235       continue;
1236 
1237     if (CurrentPHINode->getNumIncomingValues() == 2) {
1238       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1239            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1240           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1241            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1242         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1243           // The existing PHI (CurrentPHINode) has the same start and increment
1244           // as the PHI that we wanted to create.
1245           if (Form == UpdateForm &&
1246               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1247             ++PHINodeAlreadyExistsUpdate;
1248             return true;
1249           }
1250           if (Form == DSForm || Form == DQForm) {
1251             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1252                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1253             if (Diff && !Diff->getAPInt().urem(Form)) {
1254               if (Form == DSForm)
1255                 ++PHINodeAlreadyExistsDS;
1256               else
1257                 ++PHINodeAlreadyExistsDQ;
1258               return true;
1259             }
1260           }
1261         }
1262       }
1263     }
1264   }
1265   return false;
1266 }
1267 
1268 bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1269   bool MadeChange = false;
1270 
1271   // Only prep. the inner-most loop
1272   if (!L->isInnermost())
1273     return MadeChange;
1274 
1275   // Return if already done enough preparation.
1276   if (SuccPrepCount >= MaxVarsPrep)
1277     return MadeChange;
1278 
1279   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1280 
1281   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1282   // If there is no loop predecessor, or the loop predecessor's terminator
1283   // returns a value (which might contribute to determining the loop's
1284   // iteration space), insert a new preheader for the loop.
1285   if (!LoopPredecessor ||
1286       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1287     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1288     if (LoopPredecessor)
1289       MadeChange = true;
1290   }
1291   if (!LoopPredecessor) {
1292     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1293     return MadeChange;
1294   }
1295   // Check if a load/store has update form. This lambda is used by function
1296   // collectCandidates which can collect candidates for types defined by lambda.
1297   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1298                                    const Type *PointerElementType) {
1299     assert((PtrValue && I) && "Invalid parameter!");
1300     // There are no update forms for Altivec vector load/stores.
1301     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1302       return false;
1303     // There are no update forms for P10 lxvp/stxvp intrinsic.
1304     auto *II = dyn_cast<IntrinsicInst>(I);
1305     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1306                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1307       return false;
1308     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1309     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1310     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1311     // useless and possible to break some original well-form addressing mode
1312     // to make this pre-inc prep for it.
1313     if (PointerElementType->isIntegerTy(64)) {
1314       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
1315       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1316       if (!LARSCEV || LARSCEV->getLoop() != L)
1317         return false;
1318       if (const SCEVConstant *StepConst =
1319               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
1320         const APInt &ConstInt = StepConst->getValue()->getValue();
1321         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1322           return false;
1323       }
1324     }
1325     return true;
1326   };
1327 
1328   // Check if a load/store has DS form.
1329   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1330                               const Type *PointerElementType) {
1331     assert((PtrValue && I) && "Invalid parameter!");
1332     if (isa<IntrinsicInst>(I))
1333       return false;
1334     return (PointerElementType->isIntegerTy(64)) ||
1335            (PointerElementType->isFloatTy()) ||
1336            (PointerElementType->isDoubleTy()) ||
1337            (PointerElementType->isIntegerTy(32) &&
1338             llvm::any_of(I->users(),
1339                          [](const User *U) { return isa<SExtInst>(U); }));
1340   };
1341 
1342   // Check if a load/store has DQ form.
1343   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1344                                const Type *PointerElementType) {
1345     assert((PtrValue && I) && "Invalid parameter!");
1346     // Check if it is a P10 lxvp/stxvp intrinsic.
1347     auto *II = dyn_cast<IntrinsicInst>(I);
1348     if (II)
1349       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1350              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1351     // Check if it is a P9 vector load/store.
1352     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1353   };
1354 
1355   // Check if a load/store is candidate for chain commoning.
1356   // If the SCEV is only with one ptr operand in its start, we can use that
1357   // start as a chain separator. Mark this load/store as a candidate.
1358   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1359                                        const Type *PointerElementType) {
1360     const SCEVAddRecExpr *ARSCEV =
1361         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1362     if (!ARSCEV)
1363       return false;
1364 
1365     if (!ARSCEV->isAffine())
1366       return false;
1367 
1368     const SCEV *Start = ARSCEV->getStart();
1369 
1370     // A single pointer. We can treat it as offset 0.
1371     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1372       return true;
1373 
1374     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1375 
1376     // We need a SCEVAddExpr to include both base and offset.
1377     if (!ASCEV)
1378       return false;
1379 
1380     // Make sure there is only one pointer operand(base) and all other operands
1381     // are integer type.
1382     bool SawPointer = false;
1383     for (const SCEV *Op : ASCEV->operands()) {
1384       if (Op->getType()->isPointerTy()) {
1385         if (SawPointer)
1386           return false;
1387         SawPointer = true;
1388       } else if (!Op->getType()->isIntegerTy())
1389         return false;
1390     }
1391 
1392     return SawPointer;
1393   };
1394 
1395   // Check if the diff is a constant type. This is used for update/DS/DQ form
1396   // preparation.
1397   auto isValidConstantDiff = [](const SCEV *Diff) {
1398     return dyn_cast<SCEVConstant>(Diff) != nullptr;
1399   };
1400 
1401   // Make sure the diff between the base and new candidate is required type.
1402   // This is used for chain commoning preparation.
1403   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1404     assert(Diff && "Invalid Diff!\n");
1405 
1406     // Don't mess up previous dform prepare.
1407     if (isa<SCEVConstant>(Diff))
1408       return false;
1409 
1410     // A single integer type offset.
1411     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1412       return true;
1413 
1414     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1415     if (!ADiff)
1416       return false;
1417 
1418     for (const SCEV *Op : ADiff->operands())
1419       if (!Op->getType()->isIntegerTy())
1420         return false;
1421 
1422     return true;
1423   };
1424 
1425   HasCandidateForPrepare = false;
1426 
1427   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1428   // Collect buckets of comparable addresses used by loads and stores for update
1429   // form.
1430   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
1431       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
1432 
1433   // Prepare for update form.
1434   if (!UpdateFormBuckets.empty())
1435     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1436   else if (!HasCandidateForPrepare) {
1437     LLVM_DEBUG(
1438         dbgs()
1439         << "No prepare candidates found, stop praparation for current loop!\n");
1440     // If no candidate for preparing, return early.
1441     return MadeChange;
1442   }
1443 
1444   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1445   // Collect buckets of comparable addresses used by loads and stores for DS
1446   // form.
1447   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1448       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
1449 
1450   // Prepare for DS form.
1451   if (!DSFormBuckets.empty())
1452     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1453 
1454   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1455   // Collect buckets of comparable addresses used by loads and stores for DQ
1456   // form.
1457   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1458       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
1459 
1460   // Prepare for DQ form.
1461   if (!DQFormBuckets.empty())
1462     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1463 
1464   // Collect buckets of comparable addresses used by loads and stores for chain
1465   // commoning. With chain commoning, we reuse offsets between the chains, so
1466   // the register pressure will be reduced.
1467   if (!EnableChainCommoning) {
1468     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1469     return MadeChange;
1470   }
1471 
1472   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1473   SmallVector<Bucket, 16> Buckets =
1474       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1475                         MaxVarsChainCommon);
1476 
1477   // Prepare for chain commoning.
1478   if (!Buckets.empty())
1479     MadeChange |= chainCommoning(L, Buckets);
1480 
1481   return MadeChange;
1482 }
1483