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