[PowerPC] Fix LoopPreIncPrep not to depend on SCEV constant simplifications
[oota-llvm.git] / lib / Target / PowerPC / PPCLoopPreIncPrep.cpp
1 //===------ PPCLoopPreIncPrep.cpp - Loop Pre-Inc. AM Prep. Pass -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a pass to prepare loops for pre-increment addressing
11 // modes. Additional PHIs are created for loop induction variables used by
12 // load/store instructions so that the pre-increment forms can be used.
13 // Generically, this means transforming loops like this:
14 //   for (int i = 0; i < n; ++i)
15 //     array[i] = c;
16 // to look like this:
17 //   T *p = array[-1];
18 //   for (int i = 0; i < n; ++i)
19 //     *++p = c;
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "ppc-loop-preinc-prep"
23 #include "PPC.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/CodeMetrics.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/ScalarEvolution.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Transforms/Utils/LoopUtils.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
48 using namespace llvm;
49
50 // By default, we limit this to creating 16 PHIs (which is a little over half
51 // of the allocatable register set).
52 static cl::opt<unsigned> MaxVars("ppc-preinc-prep-max-vars",
53                                  cl::Hidden, cl::init(16),
54   cl::desc("Potential PHI threshold for PPC preinc loop prep"));
55
56 namespace llvm {
57   void initializePPCLoopPreIncPrepPass(PassRegistry&);
58 }
59
60 namespace {
61
62   class PPCLoopPreIncPrep : public FunctionPass {
63   public:
64     static char ID; // Pass ID, replacement for typeid
65     PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
66       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
67     }
68     PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
69       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
70     }
71
72     void getAnalysisUsage(AnalysisUsage &AU) const override {
73       AU.addPreserved<DominatorTreeWrapperPass>();
74       AU.addRequired<LoopInfoWrapperPass>();
75       AU.addPreserved<LoopInfoWrapperPass>();
76       AU.addRequired<ScalarEvolutionWrapperPass>();
77     }
78
79     bool runOnFunction(Function &F) override;
80
81     bool runOnLoop(Loop *L);
82     void simplifyLoopLatch(Loop *L);
83     bool rotateLoop(Loop *L);
84
85   private:
86     PPCTargetMachine *TM;
87     LoopInfo *LI;
88     ScalarEvolution *SE;
89   };
90 }
91
92 char PPCLoopPreIncPrep::ID = 0;
93 static const char *name = "Prepare loop for pre-inc. addressing modes";
94 INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
95 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
96 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
97 INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
98
99 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
100   return new PPCLoopPreIncPrep(TM);
101 }
102
103 namespace {
104   struct BucketElement {
105     BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
106     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
107
108     const SCEVConstant *Offset;
109     Instruction *Instr;
110   };
111
112   struct Bucket {
113     Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
114                                             Elements(1, BucketElement(I)) {}
115
116     const SCEV *BaseSCEV;
117     SmallVector<BucketElement, 16> Elements;
118   };
119 }
120
121 static bool IsPtrInBounds(Value *BasePtr) {
122   Value *StrippedBasePtr = BasePtr;
123   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
124     StrippedBasePtr = BC->getOperand(0);
125   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
126     return GEP->isInBounds();
127
128   return false;
129 }
130
131 static Value *GetPointerOperand(Value *MemI) {
132   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
133     return LMemI->getPointerOperand();
134   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
135     return SMemI->getPointerOperand();
136   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
137     if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
138       return IMemI->getArgOperand(0);
139   }
140
141   return 0;
142 }
143
144 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
145   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
146   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
147
148   bool MadeChange = false;
149
150   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
151     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
152       MadeChange |= runOnLoop(*L);
153
154   return MadeChange;
155 }
156
157 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
158   bool MadeChange = false;
159
160   // Only prep. the inner-most loop
161   if (!L->empty())
162     return MadeChange;
163
164   DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
165
166   BasicBlock *Header = L->getHeader();
167
168   const PPCSubtarget *ST =
169     TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
170
171   unsigned HeaderLoopPredCount =
172     std::distance(pred_begin(Header), pred_end(Header));
173
174   // Collect buckets of comparable addresses used by loads and stores.
175   SmallVector<Bucket, 16> Buckets;
176   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
177        I != IE; ++I) {
178     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
179         J != JE; ++J) {
180       Value *PtrValue;
181       Instruction *MemI;
182
183       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
184         MemI = LMemI;
185         PtrValue = LMemI->getPointerOperand();
186       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
187         MemI = SMemI;
188         PtrValue = SMemI->getPointerOperand();
189       } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
190         if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
191           MemI = IMemI;
192           PtrValue = IMemI->getArgOperand(0);
193         } else continue;
194       } else continue;
195
196       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
197       if (PtrAddrSpace)
198         continue;
199
200       // There are no update forms for Altivec vector load/stores.
201       if (ST && ST->hasAltivec() &&
202           PtrValue->getType()->getPointerElementType()->isVectorTy())
203         continue;
204
205       if (L->isLoopInvariant(PtrValue))
206         continue;
207
208       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
209       if (const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV)) {
210         if (LARSCEV->getLoop() != L)
211           continue;
212       } else {
213         continue;
214       }
215
216       bool FoundBucket = false;
217       for (auto &B : Buckets) {
218         const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
219         if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
220           B.Elements.push_back(BucketElement(CDiff, MemI));
221           FoundBucket = true;
222           break;
223         }
224       }
225
226       if (!FoundBucket) {
227         if (Buckets.size() == MaxVars)
228           return MadeChange;
229         Buckets.push_back(Bucket(LSCEV, MemI));
230       }
231     }
232   }
233
234   if (Buckets.empty())
235     return MadeChange;
236
237   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
238   // If there is no loop predecessor, or the loop predecessor's terminator
239   // returns a value (which might contribute to determining the loop's
240   // iteration space), insert a new preheader for the loop.
241   if (!LoopPredecessor ||
242       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
243     LoopPredecessor = InsertPreheaderForLoop(L, this);
244     if (LoopPredecessor)
245       MadeChange = true;
246   }
247   if (!LoopPredecessor)
248     return MadeChange;
249
250   DEBUG(dbgs() << "PIP: Found " << Buckets.size() << " buckets\n");
251
252   SmallSet<BasicBlock *, 16> BBChanged;
253   for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
254     // The base address of each bucket is transformed into a phi and the others
255     // are rewritten as offsets of that variable.
256
257     // We have a choice now of which instruction's memory operand we use as the
258     // base for the generated PHI. Always picking the first instruction in each
259     // bucket does not work well, specifically because that instruction might
260     // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
261     // the choice is somewhat arbitrary, because the backend will happily
262     // generate direct offsets from both the pre-incremented and
263     // post-incremented pointer values. Thus, we'll pick the first non-prefetch
264     // instruction in each bucket, and adjust the recurrence and other offsets
265     // accordingly. 
266     for (int j = 0, je = Buckets[i].Elements.size(); j != je; ++j) {
267       if (auto *II = dyn_cast<IntrinsicInst>(Buckets[i].Elements[j].Instr))
268         if (II->getIntrinsicID() == Intrinsic::prefetch)
269           continue;
270
271       // If we'd otherwise pick the first element anyway, there's nothing to do.
272       if (j == 0)
273         break;
274
275       // If our chosen element has no offset from the base pointer, there's
276       // nothing to do.
277       if (!Buckets[i].Elements[j].Offset ||
278           Buckets[i].Elements[j].Offset->isZero())
279         break;
280
281       const SCEV *Offset = Buckets[i].Elements[j].Offset;
282       Buckets[i].BaseSCEV = SE->getAddExpr(Buckets[i].BaseSCEV, Offset);
283       for (auto &E : Buckets[i].Elements) {
284         if (E.Offset)
285           E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
286         else
287           E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
288       }
289
290       std::swap(Buckets[i].Elements[j], Buckets[i].Elements[0]);
291       break;
292     }
293
294     const SCEVAddRecExpr *BasePtrSCEV =
295       cast<SCEVAddRecExpr>(Buckets[i].BaseSCEV);
296     if (!BasePtrSCEV->isAffine())
297       continue;
298
299     DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
300     assert(BasePtrSCEV->getLoop() == L &&
301            "AddRec for the wrong loop?");
302
303     // The instruction corresponding to the Bucket's BaseSCEV must be the first
304     // in the vector of elements.
305     Instruction *MemI = Buckets[i].Elements.begin()->Instr;
306     Value *BasePtr = GetPointerOperand(MemI);
307     assert(BasePtr && "No pointer operand");
308
309     Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
310     Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
311       BasePtr->getType()->getPointerAddressSpace());
312
313     const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
314     if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
315       continue;
316
317     const SCEVConstant *BasePtrIncSCEV =
318       dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
319     if (!BasePtrIncSCEV)
320       continue;
321     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
322     if (!isSafeToExpand(BasePtrStartSCEV, *SE))
323       continue;
324
325     DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
326
327     PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
328       MemI->hasName() ? MemI->getName() + ".phi" : "",
329       Header->getFirstNonPHI());
330
331     SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
332     Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
333       LoopPredecessor->getTerminator());
334
335     // Note that LoopPredecessor might occur in the predecessor list multiple
336     // times, and we need to add it the right number of times.
337     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
338          PI != PE; ++PI) {
339       if (*PI != LoopPredecessor)
340         continue;
341
342       NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
343     }
344
345     Instruction *InsPoint = &*Header->getFirstInsertionPt();
346     GetElementPtrInst *PtrInc = GetElementPtrInst::Create(
347         I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
348         MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
349     PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
350     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
351          PI != PE; ++PI) {
352       if (*PI == LoopPredecessor)
353         continue;
354
355       NewPHI->addIncoming(PtrInc, *PI);
356     }
357
358     Instruction *NewBasePtr;
359     if (PtrInc->getType() != BasePtr->getType())
360       NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
361         PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
362     else
363       NewBasePtr = PtrInc;
364
365     if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
366       BBChanged.insert(IDel->getParent());
367     BasePtr->replaceAllUsesWith(NewBasePtr);
368     RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
369
370     // Keep track of the replacement pointer values we've inserted so that we
371     // don't generate more pointer values than necessary.
372     SmallPtrSet<Value *, 16> NewPtrs;
373     NewPtrs.insert( NewBasePtr);
374
375     for (auto I = std::next(Buckets[i].Elements.begin()),
376          IE = Buckets[i].Elements.end(); I != IE; ++I) {
377       Value *Ptr = GetPointerOperand(I->Instr);
378       assert(Ptr && "No pointer operand");
379       if (NewPtrs.count(Ptr))
380         continue;
381
382       Instruction *RealNewPtr;
383       if (!I->Offset || I->Offset->getValue()->isZero()) {
384         RealNewPtr = NewBasePtr;
385       } else {
386         Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
387         if (PtrIP && isa<Instruction>(NewBasePtr) &&
388             cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
389           PtrIP = 0;
390         else if (isa<PHINode>(PtrIP))
391           PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
392         else if (!PtrIP)
393           PtrIP = I->Instr;
394
395         GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
396             I8Ty, PtrInc, I->Offset->getValue(),
397             I->Instr->hasName() ? I->Instr->getName() + ".off" : "", PtrIP);
398         if (!PtrIP)
399           NewPtr->insertAfter(cast<Instruction>(PtrInc));
400         NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
401         RealNewPtr = NewPtr;
402       }
403
404       if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
405         BBChanged.insert(IDel->getParent());
406
407       Instruction *ReplNewPtr;
408       if (Ptr->getType() != RealNewPtr->getType()) {
409         ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
410           Ptr->hasName() ? Ptr->getName() + ".cast" : "");
411         ReplNewPtr->insertAfter(RealNewPtr);
412       } else
413         ReplNewPtr = RealNewPtr;
414
415       Ptr->replaceAllUsesWith(ReplNewPtr);
416       RecursivelyDeleteTriviallyDeadInstructions(Ptr);
417
418       NewPtrs.insert(RealNewPtr);
419     }
420
421     MadeChange = true;
422   }
423
424   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
425        I != IE; ++I) {
426     if (BBChanged.count(*I))
427       DeleteDeadPHIs(*I);
428   }
429
430   return MadeChange;
431 }
432