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"
48using 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).
52static 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
56namespace llvm {
57  void initializePPCLoopPreIncPrepPass(PassRegistry&);
58}
59
60namespace {
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    DominatorTree *DT;
88    LoopInfo *LI;
89    ScalarEvolution *SE;
90    bool PreserveLCSSA;
91  };
92}
93
94char PPCLoopPreIncPrep::ID = 0;
95static const char *name = "Prepare loop for pre-inc. addressing modes";
96INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
97INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
98INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
99INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
100
101FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
102  return new PPCLoopPreIncPrep(TM);
103}
104
105namespace {
106  struct BucketElement {
107    BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
108    BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
109
110    const SCEVConstant *Offset;
111    Instruction *Instr;
112  };
113
114  struct Bucket {
115    Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
116                                            Elements(1, BucketElement(I)) {}
117
118    const SCEV *BaseSCEV;
119    SmallVector<BucketElement, 16> Elements;
120  };
121}
122
123static bool IsPtrInBounds(Value *BasePtr) {
124  Value *StrippedBasePtr = BasePtr;
125  while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
126    StrippedBasePtr = BC->getOperand(0);
127  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
128    return GEP->isInBounds();
129
130  return false;
131}
132
133static Value *GetPointerOperand(Value *MemI) {
134  if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
135    return LMemI->getPointerOperand();
136  } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
137    return SMemI->getPointerOperand();
138  } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
139    if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
140      return IMemI->getArgOperand(0);
141  }
142
143  return 0;
144}
145
146bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
147  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
148  SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
149  auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
150  DT = DTWP ? &DTWP->getDomTree() : nullptr;
151  PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
152
153  bool MadeChange = false;
154
155  for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
156    for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
157      MadeChange |= runOnLoop(*L);
158
159  return MadeChange;
160}
161
162bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
163  bool MadeChange = false;
164
165  // Only prep. the inner-most loop
166  if (!L->empty())
167    return MadeChange;
168
169  DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
170
171  BasicBlock *Header = L->getHeader();
172
173  const PPCSubtarget *ST =
174    TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
175
176  unsigned HeaderLoopPredCount =
177    std::distance(pred_begin(Header), pred_end(Header));
178
179  // Collect buckets of comparable addresses used by loads and stores.
180  SmallVector<Bucket, 16> Buckets;
181  for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
182       I != IE; ++I) {
183    for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
184        J != JE; ++J) {
185      Value *PtrValue;
186      Instruction *MemI;
187
188      if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
189        MemI = LMemI;
190        PtrValue = LMemI->getPointerOperand();
191      } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
192        MemI = SMemI;
193        PtrValue = SMemI->getPointerOperand();
194      } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
195        if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
196          MemI = IMemI;
197          PtrValue = IMemI->getArgOperand(0);
198        } else continue;
199      } else continue;
200
201      unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
202      if (PtrAddrSpace)
203        continue;
204
205      // There are no update forms for Altivec vector load/stores.
206      if (ST && ST->hasAltivec() &&
207          PtrValue->getType()->getPointerElementType()->isVectorTy())
208        continue;
209
210      if (L->isLoopInvariant(PtrValue))
211        continue;
212
213      const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
214      if (const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV)) {
215        if (LARSCEV->getLoop() != L)
216          continue;
217      } else {
218        continue;
219      }
220
221      bool FoundBucket = false;
222      for (auto &B : Buckets) {
223        const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
224        if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
225          B.Elements.push_back(BucketElement(CDiff, MemI));
226          FoundBucket = true;
227          break;
228        }
229      }
230
231      if (!FoundBucket) {
232        if (Buckets.size() == MaxVars)
233          return MadeChange;
234        Buckets.push_back(Bucket(LSCEV, MemI));
235      }
236    }
237  }
238
239  if (Buckets.empty())
240    return MadeChange;
241
242  BasicBlock *LoopPredecessor = L->getLoopPredecessor();
243  // If there is no loop predecessor, or the loop predecessor's terminator
244  // returns a value (which might contribute to determining the loop's
245  // iteration space), insert a new preheader for the loop.
246  if (!LoopPredecessor ||
247      !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
248    LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
249    if (LoopPredecessor)
250      MadeChange = true;
251  }
252  if (!LoopPredecessor)
253    return MadeChange;
254
255  DEBUG(dbgs() << "PIP: Found " << Buckets.size() << " buckets\n");
256
257  SmallSet<BasicBlock *, 16> BBChanged;
258  for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
259    // The base address of each bucket is transformed into a phi and the others
260    // are rewritten as offsets of that variable.
261
262    // We have a choice now of which instruction's memory operand we use as the
263    // base for the generated PHI. Always picking the first instruction in each
264    // bucket does not work well, specifically because that instruction might
265    // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
266    // the choice is somewhat arbitrary, because the backend will happily
267    // generate direct offsets from both the pre-incremented and
268    // post-incremented pointer values. Thus, we'll pick the first non-prefetch
269    // instruction in each bucket, and adjust the recurrence and other offsets
270    // accordingly.
271    for (int j = 0, je = Buckets[i].Elements.size(); j != je; ++j) {
272      if (auto *II = dyn_cast<IntrinsicInst>(Buckets[i].Elements[j].Instr))
273        if (II->getIntrinsicID() == Intrinsic::prefetch)
274          continue;
275
276      // If we'd otherwise pick the first element anyway, there's nothing to do.
277      if (j == 0)
278        break;
279
280      // If our chosen element has no offset from the base pointer, there's
281      // nothing to do.
282      if (!Buckets[i].Elements[j].Offset ||
283          Buckets[i].Elements[j].Offset->isZero())
284        break;
285
286      const SCEV *Offset = Buckets[i].Elements[j].Offset;
287      Buckets[i].BaseSCEV = SE->getAddExpr(Buckets[i].BaseSCEV, Offset);
288      for (auto &E : Buckets[i].Elements) {
289        if (E.Offset)
290          E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
291        else
292          E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
293      }
294
295      std::swap(Buckets[i].Elements[j], Buckets[i].Elements[0]);
296      break;
297    }
298
299    const SCEVAddRecExpr *BasePtrSCEV =
300      cast<SCEVAddRecExpr>(Buckets[i].BaseSCEV);
301    if (!BasePtrSCEV->isAffine())
302      continue;
303
304    DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
305    assert(BasePtrSCEV->getLoop() == L &&
306           "AddRec for the wrong loop?");
307
308    // The instruction corresponding to the Bucket's BaseSCEV must be the first
309    // in the vector of elements.
310    Instruction *MemI = Buckets[i].Elements.begin()->Instr;
311    Value *BasePtr = GetPointerOperand(MemI);
312    assert(BasePtr && "No pointer operand");
313
314    Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
315    Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
316      BasePtr->getType()->getPointerAddressSpace());
317
318    const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
319    if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
320      continue;
321
322    const SCEVConstant *BasePtrIncSCEV =
323      dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
324    if (!BasePtrIncSCEV)
325      continue;
326    BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
327    if (!isSafeToExpand(BasePtrStartSCEV, *SE))
328      continue;
329
330    DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
331
332    PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
333      MemI->hasName() ? MemI->getName() + ".phi" : "",
334      Header->getFirstNonPHI());
335
336    SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
337    Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
338      LoopPredecessor->getTerminator());
339
340    // Note that LoopPredecessor might occur in the predecessor list multiple
341    // times, and we need to add it the right number of times.
342    for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
343         PI != PE; ++PI) {
344      if (*PI != LoopPredecessor)
345        continue;
346
347      NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
348    }
349
350    Instruction *InsPoint = &*Header->getFirstInsertionPt();
351    GetElementPtrInst *PtrInc = GetElementPtrInst::Create(
352        I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
353        MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
354    PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
355    for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
356         PI != PE; ++PI) {
357      if (*PI == LoopPredecessor)
358        continue;
359
360      NewPHI->addIncoming(PtrInc, *PI);
361    }
362
363    Instruction *NewBasePtr;
364    if (PtrInc->getType() != BasePtr->getType())
365      NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
366        PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
367    else
368      NewBasePtr = PtrInc;
369
370    if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
371      BBChanged.insert(IDel->getParent());
372    BasePtr->replaceAllUsesWith(NewBasePtr);
373    RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
374
375    // Keep track of the replacement pointer values we've inserted so that we
376    // don't generate more pointer values than necessary.
377    SmallPtrSet<Value *, 16> NewPtrs;
378    NewPtrs.insert( NewBasePtr);
379
380    for (auto I = std::next(Buckets[i].Elements.begin()),
381         IE = Buckets[i].Elements.end(); I != IE; ++I) {
382      Value *Ptr = GetPointerOperand(I->Instr);
383      assert(Ptr && "No pointer operand");
384      if (NewPtrs.count(Ptr))
385        continue;
386
387      Instruction *RealNewPtr;
388      if (!I->Offset || I->Offset->getValue()->isZero()) {
389        RealNewPtr = NewBasePtr;
390      } else {
391        Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
392        if (PtrIP && isa<Instruction>(NewBasePtr) &&
393            cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
394          PtrIP = 0;
395        else if (isa<PHINode>(PtrIP))
396          PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
397        else if (!PtrIP)
398          PtrIP = I->Instr;
399
400        GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
401            I8Ty, PtrInc, I->Offset->getValue(),
402            I->Instr->hasName() ? I->Instr->getName() + ".off" : "", PtrIP);
403        if (!PtrIP)
404          NewPtr->insertAfter(cast<Instruction>(PtrInc));
405        NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
406        RealNewPtr = NewPtr;
407      }
408
409      if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
410        BBChanged.insert(IDel->getParent());
411
412      Instruction *ReplNewPtr;
413      if (Ptr->getType() != RealNewPtr->getType()) {
414        ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
415          Ptr->hasName() ? Ptr->getName() + ".cast" : "");
416        ReplNewPtr->insertAfter(RealNewPtr);
417      } else
418        ReplNewPtr = RealNewPtr;
419
420      Ptr->replaceAllUsesWith(ReplNewPtr);
421      RecursivelyDeleteTriviallyDeadInstructions(Ptr);
422
423      NewPtrs.insert(RealNewPtr);
424    }
425
426    MadeChange = true;
427  }
428
429  for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
430       I != IE; ++I) {
431    if (BBChanged.count(*I))
432      DeleteDeadPHIs(*I);
433  }
434
435  return MadeChange;
436}
437
438