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