1aba58f8af27aeac3e4ebf6573d702dc78568e36
[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/Transforms/Scalar.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.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/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/ValueMapper.h"
45 using namespace llvm;
46
47 // By default, we limit this to creating 16 PHIs (which is a little over half
48 // of the allocatable register set).
49 static cl::opt<unsigned> MaxVars("ppc-preinc-prep-max-vars",
50                                  cl::Hidden, cl::init(16),
51   cl::desc("Potential PHI threshold for PPC preinc loop prep"));
52
53 namespace llvm {
54   void initializePPCLoopPreIncPrepPass(PassRegistry&);
55 }
56
57 namespace {
58
59   class PPCLoopPreIncPrep : public FunctionPass {
60   public:
61     static char ID; // Pass ID, replacement for typeid
62     PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
63       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
64     }
65     PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
66       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
67     }
68
69     void getAnalysisUsage(AnalysisUsage &AU) const override {
70       AU.addPreserved<DominatorTreeWrapperPass>();
71       AU.addRequired<LoopInfoWrapperPass>();
72       AU.addPreserved<LoopInfoWrapperPass>();
73       AU.addRequired<ScalarEvolution>();
74     }
75
76     bool runOnFunction(Function &F) override;
77
78     bool runOnLoop(Loop *L);
79     void simplifyLoopLatch(Loop *L);
80     bool rotateLoop(Loop *L);
81
82   private:
83     PPCTargetMachine *TM;
84     LoopInfo *LI;
85     ScalarEvolution *SE;
86     const DataLayout *DL;
87   };
88 }
89
90 char PPCLoopPreIncPrep::ID = 0;
91 const char *name = "Prepare loop for pre-inc. addressing modes";
92 INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
93 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
94 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
95 INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
96
97 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
98   return new PPCLoopPreIncPrep(TM);
99 }
100
101 namespace {
102   struct SCEVLess : std::binary_function<const SCEV *, const SCEV *, bool>
103   {
104     SCEVLess(ScalarEvolution *SE) : SE(SE) {}
105
106     bool operator() (const SCEV *X, const SCEV *Y) const {
107       const SCEV *Diff = SE->getMinusSCEV(X, Y);
108       return cast<SCEVConstant>(Diff)->getValue()->getSExtValue() < 0;
109     }
110
111   protected:
112     ScalarEvolution *SE;
113   };
114 }
115
116 static bool IsPtrInBounds(Value *BasePtr) {
117   Value *StrippedBasePtr = BasePtr;
118   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
119     StrippedBasePtr = BC->getOperand(0);
120   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
121     return GEP->isInBounds();
122
123   return false;
124 }
125
126 static Value *GetPointerOperand(Value *MemI) {
127   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
128     return LMemI->getPointerOperand();
129   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
130     return SMemI->getPointerOperand();
131   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
132     if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
133       return IMemI->getArgOperand(0);
134   }
135
136   return 0;
137 }
138
139 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
140   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
141   SE = &getAnalysis<ScalarEvolution>();
142
143   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
144   DL = DLP ? &DLP->getDataLayout() : 0;
145
146   bool MadeChange = false;
147
148   for (LoopInfo::iterator I = LI->begin(), E = LI->end();
149        I != E; ++I) {
150     Loop *L = *I;
151     MadeChange |= runOnLoop(L);
152   }
153
154   return MadeChange;
155 }
156
157 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
158   bool MadeChange = false;
159
160   if (!DL)
161     return MadeChange;
162
163   // Only prep. the inner-most loop
164   if (!L->empty())
165     return MadeChange;
166
167   BasicBlock *Header = L->getHeader();
168   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
169   if (!LoopPredecessor)
170     return MadeChange;
171
172   const PPCSubtarget *ST =
173     TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
174
175   unsigned HeaderLoopPredCount = 0;
176   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
177        PI != PE; ++PI) {
178     ++HeaderLoopPredCount;
179   }
180
181   // Collect buckets of comparable addresses used by loads and stores.
182   typedef std::multimap<const SCEV *, Instruction *, SCEVLess> Bucket;
183   SmallVector<Bucket, 16> Buckets;
184   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
185        I != IE; ++I) {
186     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
187         J != JE; ++J) {
188       Value *PtrValue;
189       Instruction *MemI;
190
191       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
192         MemI = LMemI;
193         PtrValue = LMemI->getPointerOperand();
194       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
195         MemI = SMemI;
196         PtrValue = SMemI->getPointerOperand();
197       } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
198         if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
199           MemI = IMemI;
200           PtrValue = IMemI->getArgOperand(0);
201         } else continue;
202       } else continue;
203
204       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
205       if (PtrAddrSpace)
206         continue;
207
208       // There are no update forms for Altivec vector load/stores.
209       if (ST && ST->hasAltivec() &&
210           PtrValue->getType()->getPointerElementType()->isVectorTy())
211         continue;
212
213       if (L->isLoopInvariant(PtrValue))
214         continue;
215
216       const SCEV *LSCEV = SE->getSCEV(PtrValue);
217       if (!isa<SCEVAddRecExpr>(LSCEV))
218         continue;
219
220       bool FoundBucket = false;
221       for (unsigned i = 0, e = Buckets.size(); i != e; ++i)
222         for (Bucket::iterator K = Buckets[i].begin(), KE = Buckets[i].end();
223              K != KE; ++K) {
224           const SCEV *Diff = SE->getMinusSCEV(K->first, LSCEV);
225           if (isa<SCEVConstant>(Diff)) {
226             Buckets[i].insert(std::make_pair(LSCEV, MemI));
227             FoundBucket = true;
228             break;
229           }
230         }
231
232       if (!FoundBucket) {
233         Buckets.push_back(Bucket(SCEVLess(SE)));
234         Buckets[Buckets.size()-1].insert(std::make_pair(LSCEV, MemI));
235       }
236     }
237   }
238
239   if (Buckets.size() > MaxVars)
240     return MadeChange;
241
242   SmallSet<BasicBlock *, 16> BBChanged;
243   for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
244     // The base address of each bucket is transformed into a phi and the others
245     // are rewritten as offsets of that variable.
246
247     const SCEVAddRecExpr *BasePtrSCEV =
248       cast<SCEVAddRecExpr>(Buckets[i].begin()->first);
249     if (!BasePtrSCEV->isAffine())
250       continue;
251
252     Instruction *MemI = Buckets[i].begin()->second;
253     Value *BasePtr = GetPointerOperand(MemI);
254     assert(BasePtr && "No pointer operand");
255
256     Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
257       BasePtr->getType()->getPointerAddressSpace());
258
259     const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
260     if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
261       continue;
262
263     const SCEVConstant *BasePtrIncSCEV =
264       dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
265     if (!BasePtrIncSCEV)
266       continue;
267     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
268     if (!isSafeToExpand(BasePtrStartSCEV, *SE))
269       continue;
270
271     PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
272       MemI->hasName() ? MemI->getName() + ".phi" : "",
273       Header->getFirstNonPHI());
274
275     SCEVExpander SCEVE(*SE, "pistart");
276     Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
277       LoopPredecessor->getTerminator());
278
279     // Note that LoopPredecessor might occur in the predecessor list multiple
280     // times, and we need to add it the right number of times.
281     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
282          PI != PE; ++PI) {
283       if (*PI != LoopPredecessor)
284         continue;
285
286       NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
287     }
288
289     Instruction *InsPoint = Header->getFirstInsertionPt();
290     GetElementPtrInst *PtrInc =
291       GetElementPtrInst::Create(NewPHI, BasePtrIncSCEV->getValue(),
292         MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
293     PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
294     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
295          PI != PE; ++PI) {
296       if (*PI == LoopPredecessor)
297         continue;
298
299       NewPHI->addIncoming(PtrInc, *PI);
300     }
301
302     Instruction *NewBasePtr;
303     if (PtrInc->getType() != BasePtr->getType())
304       NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
305         PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
306     else
307       NewBasePtr = PtrInc;
308
309     if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
310       BBChanged.insert(IDel->getParent());
311     BasePtr->replaceAllUsesWith(NewBasePtr);
312     RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
313
314     Value *LastNewPtr = NewBasePtr;
315     for (Bucket::iterator I = std::next(Buckets[i].begin()),
316          IE = Buckets[i].end(); I != IE; ++I) {
317       Value *Ptr = GetPointerOperand(I->second);
318       assert(Ptr && "No pointer operand");
319       if (Ptr == LastNewPtr)
320         continue;
321
322       Instruction *RealNewPtr;
323       const SCEVConstant *Diff =
324         cast<SCEVConstant>(SE->getMinusSCEV(I->first, BasePtrSCEV));
325       if (Diff->isZero()) {
326         RealNewPtr = NewBasePtr;
327       } else {
328         Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
329         if (PtrIP && isa<Instruction>(NewBasePtr) &&
330             cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
331           PtrIP = 0;
332         else if (isa<PHINode>(PtrIP))
333           PtrIP = PtrIP->getParent()->getFirstInsertionPt();
334         else if (!PtrIP)
335           PtrIP = I->second;
336   
337         GetElementPtrInst *NewPtr =
338           GetElementPtrInst::Create(PtrInc, Diff->getValue(),
339             I->second->hasName() ? I->second->getName() + ".off" : "", PtrIP);
340         if (!PtrIP)
341           NewPtr->insertAfter(cast<Instruction>(PtrInc));
342         NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
343         RealNewPtr = NewPtr;
344       }
345
346       if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
347         BBChanged.insert(IDel->getParent());
348
349       Instruction *ReplNewPtr;
350       if (Ptr->getType() != RealNewPtr->getType()) {
351         ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
352           Ptr->hasName() ? Ptr->getName() + ".cast" : "");
353         ReplNewPtr->insertAfter(RealNewPtr);
354       } else
355         ReplNewPtr = RealNewPtr;
356
357       Ptr->replaceAllUsesWith(ReplNewPtr);
358       RecursivelyDeleteTriviallyDeadInstructions(Ptr);
359
360       LastNewPtr = RealNewPtr;
361     }
362
363     MadeChange = true;
364   }
365
366   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
367        I != IE; ++I) {
368     if (BBChanged.count(*I))
369       DeleteDeadPHIs(*I);
370   }
371
372   return MadeChange;
373 }
374