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"
25 #include "PPCSubtarget.h"
26 #include "PPCTargetMachine.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.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/IR/BasicBlock.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Transforms/Utils/LoopUtils.h"
57 // By default, we limit this to creating 16 PHIs (which is a little over half
58 // of the allocatable register set).
59 static cl::opt<unsigned> MaxVars("ppc-preinc-prep-max-vars",
60 cl::Hidden, cl::init(16),
61 cl::desc("Potential PHI threshold for PPC preinc loop prep"));
65 void initializePPCLoopPreIncPrepPass(PassRegistry&);
67 } // end namespace llvm
71 class PPCLoopPreIncPrep : public FunctionPass {
73 static char ID; // Pass ID, replacement for typeid
75 PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
76 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
78 PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
79 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
82 void getAnalysisUsage(AnalysisUsage &AU) const override {
83 AU.addPreserved<DominatorTreeWrapperPass>();
84 AU.addRequired<LoopInfoWrapperPass>();
85 AU.addPreserved<LoopInfoWrapperPass>();
86 AU.addRequired<ScalarEvolutionWrapperPass>();
89 bool runOnFunction(Function &F) override;
91 bool runOnLoop(Loop *L);
92 void simplifyLoopLatch(Loop *L);
93 bool rotateLoop(Loop *L);
103 } // end anonymous namespace
105 char PPCLoopPreIncPrep::ID = 0;
106 static const char *name = "Prepare loop for pre-inc. addressing modes";
107 INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
108 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
109 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
110 INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
112 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
113 return new PPCLoopPreIncPrep(TM);
118 struct BucketElement {
119 BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
120 BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
122 const SCEVConstant *Offset;
127 Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
128 Elements(1, BucketElement(I)) {}
130 const SCEV *BaseSCEV;
131 SmallVector<BucketElement, 16> Elements;
134 } // end anonymous namespace
136 static bool IsPtrInBounds(Value *BasePtr) {
137 Value *StrippedBasePtr = BasePtr;
138 while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
139 StrippedBasePtr = BC->getOperand(0);
140 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
141 return GEP->isInBounds();
146 static Value *GetPointerOperand(Value *MemI) {
147 if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
148 return LMemI->getPointerOperand();
149 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
150 return SMemI->getPointerOperand();
151 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
152 if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
153 return IMemI->getArgOperand(0);
159 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
163 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
164 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
165 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
166 DT = DTWP ? &DTWP->getDomTree() : nullptr;
167 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
169 bool MadeChange = false;
171 for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
172 for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
173 MadeChange |= runOnLoop(*L);
178 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
179 bool MadeChange = false;
181 // Only prep. the inner-most loop
185 DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
187 BasicBlock *Header = L->getHeader();
189 const PPCSubtarget *ST =
190 TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
192 unsigned HeaderLoopPredCount =
193 std::distance(pred_begin(Header), pred_end(Header));
195 // Collect buckets of comparable addresses used by loads and stores.
196 SmallVector<Bucket, 16> Buckets;
197 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
199 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
204 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
206 PtrValue = LMemI->getPointerOperand();
207 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
209 PtrValue = SMemI->getPointerOperand();
210 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
211 if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
213 PtrValue = IMemI->getArgOperand(0);
217 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
221 // There are no update forms for Altivec vector load/stores.
222 if (ST && ST->hasAltivec() &&
223 PtrValue->getType()->getPointerElementType()->isVectorTy())
226 if (L->isLoopInvariant(PtrValue))
229 const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
230 if (const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV)) {
231 if (LARSCEV->getLoop() != L)
237 bool FoundBucket = false;
238 for (auto &B : Buckets) {
239 const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
240 if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
241 B.Elements.push_back(BucketElement(CDiff, MemI));
248 if (Buckets.size() == MaxVars)
250 Buckets.push_back(Bucket(LSCEV, MemI));
258 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
259 // If there is no loop predecessor, or the loop predecessor's terminator
260 // returns a value (which might contribute to determining the loop's
261 // iteration space), insert a new preheader for the loop.
262 if (!LoopPredecessor ||
263 !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
264 LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
268 if (!LoopPredecessor)
271 DEBUG(dbgs() << "PIP: Found " << Buckets.size() << " buckets\n");
273 SmallSet<BasicBlock *, 16> BBChanged;
274 for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
275 // The base address of each bucket is transformed into a phi and the others
276 // are rewritten as offsets of that variable.
278 // We have a choice now of which instruction's memory operand we use as the
279 // base for the generated PHI. Always picking the first instruction in each
280 // bucket does not work well, specifically because that instruction might
281 // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
282 // the choice is somewhat arbitrary, because the backend will happily
283 // generate direct offsets from both the pre-incremented and
284 // post-incremented pointer values. Thus, we'll pick the first non-prefetch
285 // instruction in each bucket, and adjust the recurrence and other offsets
287 for (int j = 0, je = Buckets[i].Elements.size(); j != je; ++j) {
288 if (auto *II = dyn_cast<IntrinsicInst>(Buckets[i].Elements[j].Instr))
289 if (II->getIntrinsicID() == Intrinsic::prefetch)
292 // If we'd otherwise pick the first element anyway, there's nothing to do.
296 // If our chosen element has no offset from the base pointer, there's
298 if (!Buckets[i].Elements[j].Offset ||
299 Buckets[i].Elements[j].Offset->isZero())
302 const SCEV *Offset = Buckets[i].Elements[j].Offset;
303 Buckets[i].BaseSCEV = SE->getAddExpr(Buckets[i].BaseSCEV, Offset);
304 for (auto &E : Buckets[i].Elements) {
306 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
308 E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
311 std::swap(Buckets[i].Elements[j], Buckets[i].Elements[0]);
315 const SCEVAddRecExpr *BasePtrSCEV =
316 cast<SCEVAddRecExpr>(Buckets[i].BaseSCEV);
317 if (!BasePtrSCEV->isAffine())
320 DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
321 assert(BasePtrSCEV->getLoop() == L &&
322 "AddRec for the wrong loop?");
324 // The instruction corresponding to the Bucket's BaseSCEV must be the first
325 // in the vector of elements.
326 Instruction *MemI = Buckets[i].Elements.begin()->Instr;
327 Value *BasePtr = GetPointerOperand(MemI);
328 assert(BasePtr && "No pointer operand");
330 Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
331 Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
332 BasePtr->getType()->getPointerAddressSpace());
334 const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
335 if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
338 const SCEVConstant *BasePtrIncSCEV =
339 dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
342 BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
343 if (!isSafeToExpand(BasePtrStartSCEV, *SE))
346 DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
348 PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
349 MemI->hasName() ? MemI->getName() + ".phi" : "",
350 Header->getFirstNonPHI());
352 SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
353 Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
354 LoopPredecessor->getTerminator());
356 // Note that LoopPredecessor might occur in the predecessor list multiple
357 // times, and we need to add it the right number of times.
358 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
360 if (*PI != LoopPredecessor)
363 NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
366 Instruction *InsPoint = &*Header->getFirstInsertionPt();
367 GetElementPtrInst *PtrInc = GetElementPtrInst::Create(
368 I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
369 MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
370 PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
371 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
373 if (*PI == LoopPredecessor)
376 NewPHI->addIncoming(PtrInc, *PI);
379 Instruction *NewBasePtr;
380 if (PtrInc->getType() != BasePtr->getType())
381 NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
382 PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
386 if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
387 BBChanged.insert(IDel->getParent());
388 BasePtr->replaceAllUsesWith(NewBasePtr);
389 RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
391 // Keep track of the replacement pointer values we've inserted so that we
392 // don't generate more pointer values than necessary.
393 SmallPtrSet<Value *, 16> NewPtrs;
394 NewPtrs.insert( NewBasePtr);
396 for (auto I = std::next(Buckets[i].Elements.begin()),
397 IE = Buckets[i].Elements.end(); I != IE; ++I) {
398 Value *Ptr = GetPointerOperand(I->Instr);
399 assert(Ptr && "No pointer operand");
400 if (NewPtrs.count(Ptr))
403 Instruction *RealNewPtr;
404 if (!I->Offset || I->Offset->getValue()->isZero()) {
405 RealNewPtr = NewBasePtr;
407 Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
408 if (PtrIP && isa<Instruction>(NewBasePtr) &&
409 cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
411 else if (isa<PHINode>(PtrIP))
412 PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
416 GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
417 I8Ty, PtrInc, I->Offset->getValue(),
418 I->Instr->hasName() ? I->Instr->getName() + ".off" : "", PtrIP);
420 NewPtr->insertAfter(cast<Instruction>(PtrInc));
421 NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
425 if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
426 BBChanged.insert(IDel->getParent());
428 Instruction *ReplNewPtr;
429 if (Ptr->getType() != RealNewPtr->getType()) {
430 ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
431 Ptr->hasName() ? Ptr->getName() + ".cast" : "");
432 ReplNewPtr->insertAfter(RealNewPtr);
434 ReplNewPtr = RealNewPtr;
436 Ptr->replaceAllUsesWith(ReplNewPtr);
437 RecursivelyDeleteTriviallyDeadInstructions(Ptr);
439 NewPtrs.insert(RealNewPtr);
445 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
447 if (BBChanged.count(*I))