1 //===------ PPCLoopPreIncPrep.cpp - Loop Pre-Inc. AM Prep. Pass -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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)
18 // for (int i = 0; i < n; ++i)
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "ppc-loop-preinc-prep"
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"
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"));
54 void initializePPCLoopPreIncPrepPass(PassRegistry&);
59 class PPCLoopPreIncPrep : public FunctionPass {
61 static char ID; // Pass ID, replacement for typeid
62 PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
63 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
65 PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
66 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
69 void getAnalysisUsage(AnalysisUsage &AU) const override {
70 AU.addPreserved<DominatorTreeWrapperPass>();
71 AU.addRequired<LoopInfoWrapperPass>();
72 AU.addPreserved<LoopInfoWrapperPass>();
73 AU.addRequired<ScalarEvolution>();
76 bool runOnFunction(Function &F) override;
78 bool runOnLoop(Loop *L);
79 void simplifyLoopLatch(Loop *L);
80 bool rotateLoop(Loop *L);
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)
97 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
98 return new PPCLoopPreIncPrep(TM);
102 struct SCEVLess : std::binary_function<const SCEV *, const SCEV *, bool>
104 SCEVLess(ScalarEvolution *SE) : SE(SE) {}
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;
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();
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);
139 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
140 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
141 SE = &getAnalysis<ScalarEvolution>();
143 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
144 DL = DLP ? &DLP->getDataLayout() : 0;
146 bool MadeChange = false;
148 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
151 MadeChange |= runOnLoop(L);
157 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
158 bool MadeChange = false;
163 // Only prep. the inner-most loop
167 BasicBlock *Header = L->getHeader();
168 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
169 if (!LoopPredecessor)
172 const PPCSubtarget *ST =
173 TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
175 unsigned HeaderLoopPredCount = 0;
176 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
178 ++HeaderLoopPredCount;
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();
186 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
191 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
193 PtrValue = LMemI->getPointerOperand();
194 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
196 PtrValue = SMemI->getPointerOperand();
197 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
198 if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
200 PtrValue = IMemI->getArgOperand(0);
204 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
208 // There are no update forms for Altivec vector load/stores.
209 if (ST && ST->hasAltivec() &&
210 PtrValue->getType()->getPointerElementType()->isVectorTy())
213 if (L->isLoopInvariant(PtrValue))
216 const SCEV *LSCEV = SE->getSCEV(PtrValue);
217 if (!isa<SCEVAddRecExpr>(LSCEV))
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();
224 const SCEV *Diff = SE->getMinusSCEV(K->first, LSCEV);
225 if (isa<SCEVConstant>(Diff)) {
226 Buckets[i].insert(std::make_pair(LSCEV, MemI));
233 Buckets.push_back(Bucket(SCEVLess(SE)));
234 Buckets[Buckets.size()-1].insert(std::make_pair(LSCEV, MemI));
239 if (Buckets.size() > MaxVars)
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.
247 const SCEVAddRecExpr *BasePtrSCEV =
248 cast<SCEVAddRecExpr>(Buckets[i].begin()->first);
249 if (!BasePtrSCEV->isAffine())
252 Instruction *MemI = Buckets[i].begin()->second;
253 Value *BasePtr = GetPointerOperand(MemI);
254 assert(BasePtr && "No pointer operand");
256 Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
257 BasePtr->getType()->getPointerAddressSpace());
259 const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
260 if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
263 const SCEVConstant *BasePtrIncSCEV =
264 dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
267 BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
268 if (!isSafeToExpand(BasePtrStartSCEV, *SE))
271 PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
272 MemI->hasName() ? MemI->getName() + ".phi" : "",
273 Header->getFirstNonPHI());
275 SCEVExpander SCEVE(*SE, "pistart");
276 Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
277 LoopPredecessor->getTerminator());
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);
283 if (*PI != LoopPredecessor)
286 NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
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);
296 if (*PI == LoopPredecessor)
299 NewPHI->addIncoming(PtrInc, *PI);
302 Instruction *NewBasePtr;
303 if (PtrInc->getType() != BasePtr->getType())
304 NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
305 PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
309 if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
310 BBChanged.insert(IDel->getParent());
311 BasePtr->replaceAllUsesWith(NewBasePtr);
312 RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
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)
322 Instruction *RealNewPtr;
323 const SCEVConstant *Diff =
324 cast<SCEVConstant>(SE->getMinusSCEV(I->first, BasePtrSCEV));
325 if (Diff->isZero()) {
326 RealNewPtr = NewBasePtr;
328 Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
329 if (PtrIP && isa<Instruction>(NewBasePtr) &&
330 cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
332 else if (isa<PHINode>(PtrIP))
333 PtrIP = PtrIP->getParent()->getFirstInsertionPt();
337 GetElementPtrInst *NewPtr =
338 GetElementPtrInst::Create(PtrInc, Diff->getValue(),
339 I->second->hasName() ? I->second->getName() + ".off" : "", PtrIP);
341 NewPtr->insertAfter(cast<Instruction>(PtrInc));
342 NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
346 if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
347 BBChanged.insert(IDel->getParent());
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);
355 ReplNewPtr = RealNewPtr;
357 Ptr->replaceAllUsesWith(ReplNewPtr);
358 RecursivelyDeleteTriviallyDeadInstructions(Ptr);
360 LastNewPtr = RealNewPtr;
366 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
368 if (BBChanged.count(*I))