xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass implements an idiom recognizer that transforms simple loops into a
11*9880d681SAndroid Build Coastguard Worker // non-loop form.  In cases that this kicks in, it can be a significant
12*9880d681SAndroid Build Coastguard Worker // performance win.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
15*9880d681SAndroid Build Coastguard Worker //
16*9880d681SAndroid Build Coastguard Worker // TODO List:
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker // Future loop memory idioms to recognize:
19*9880d681SAndroid Build Coastguard Worker //   memcmp, memmove, strlen, etc.
20*9880d681SAndroid Build Coastguard Worker // Future floating point idioms to recognize in -ffast-math mode:
21*9880d681SAndroid Build Coastguard Worker //   fpowi
22*9880d681SAndroid Build Coastguard Worker // Future integer operation idioms to recognize:
23*9880d681SAndroid Build Coastguard Worker //   ctpop, ctlz, cttz
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker // Beware that isel's default lowering for ctpop is highly inefficient for
26*9880d681SAndroid Build Coastguard Worker // i64 and larger types when i64 is legal and the value has few bits set.  It
27*9880d681SAndroid Build Coastguard Worker // would be good to enhance isel to emit a loop for ctpop in this case.
28*9880d681SAndroid Build Coastguard Worker //
29*9880d681SAndroid Build Coastguard Worker // This could recognize common matrix multiplies and dot product idioms and
30*9880d681SAndroid Build Coastguard Worker // replace them with calls to BLAS (if linked in??).
31*9880d681SAndroid Build Coastguard Worker //
32*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
33*9880d681SAndroid Build Coastguard Worker 
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/MapVector.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopAccessAnalysis.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPass.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPassManager.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionExpander.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BuildLibCalls.h"
59*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
60*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
61*9880d681SAndroid Build Coastguard Worker using namespace llvm;
62*9880d681SAndroid Build Coastguard Worker 
63*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "loop-idiom"
64*9880d681SAndroid Build Coastguard Worker 
65*9880d681SAndroid Build Coastguard Worker STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66*9880d681SAndroid Build Coastguard Worker STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
67*9880d681SAndroid Build Coastguard Worker 
68*9880d681SAndroid Build Coastguard Worker namespace {
69*9880d681SAndroid Build Coastguard Worker 
70*9880d681SAndroid Build Coastguard Worker class LoopIdiomRecognize {
71*9880d681SAndroid Build Coastguard Worker   Loop *CurLoop;
72*9880d681SAndroid Build Coastguard Worker   AliasAnalysis *AA;
73*9880d681SAndroid Build Coastguard Worker   DominatorTree *DT;
74*9880d681SAndroid Build Coastguard Worker   LoopInfo *LI;
75*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE;
76*9880d681SAndroid Build Coastguard Worker   TargetLibraryInfo *TLI;
77*9880d681SAndroid Build Coastguard Worker   const TargetTransformInfo *TTI;
78*9880d681SAndroid Build Coastguard Worker   const DataLayout *DL;
79*9880d681SAndroid Build Coastguard Worker 
80*9880d681SAndroid Build Coastguard Worker public:
LoopIdiomRecognize(AliasAnalysis * AA,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,const DataLayout * DL)81*9880d681SAndroid Build Coastguard Worker   explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
82*9880d681SAndroid Build Coastguard Worker                               LoopInfo *LI, ScalarEvolution *SE,
83*9880d681SAndroid Build Coastguard Worker                               TargetLibraryInfo *TLI,
84*9880d681SAndroid Build Coastguard Worker                               const TargetTransformInfo *TTI,
85*9880d681SAndroid Build Coastguard Worker                               const DataLayout *DL)
86*9880d681SAndroid Build Coastguard Worker       : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
87*9880d681SAndroid Build Coastguard Worker         DL(DL) {}
88*9880d681SAndroid Build Coastguard Worker 
89*9880d681SAndroid Build Coastguard Worker   bool runOnLoop(Loop *L);
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker private:
92*9880d681SAndroid Build Coastguard Worker   typedef SmallVector<StoreInst *, 8> StoreList;
93*9880d681SAndroid Build Coastguard Worker   typedef MapVector<Value *, StoreList> StoreListMap;
94*9880d681SAndroid Build Coastguard Worker   StoreListMap StoreRefsForMemset;
95*9880d681SAndroid Build Coastguard Worker   StoreListMap StoreRefsForMemsetPattern;
96*9880d681SAndroid Build Coastguard Worker   StoreList StoreRefsForMemcpy;
97*9880d681SAndroid Build Coastguard Worker   bool HasMemset;
98*9880d681SAndroid Build Coastguard Worker   bool HasMemsetPattern;
99*9880d681SAndroid Build Coastguard Worker   bool HasMemcpy;
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker   /// \name Countable Loop Idiom Handling
102*9880d681SAndroid Build Coastguard Worker   /// @{
103*9880d681SAndroid Build Coastguard Worker 
104*9880d681SAndroid Build Coastguard Worker   bool runOnCountableLoop();
105*9880d681SAndroid Build Coastguard Worker   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
106*9880d681SAndroid Build Coastguard Worker                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
107*9880d681SAndroid Build Coastguard Worker 
108*9880d681SAndroid Build Coastguard Worker   void collectStores(BasicBlock *BB);
109*9880d681SAndroid Build Coastguard Worker   bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern,
110*9880d681SAndroid Build Coastguard Worker                     bool &ForMemcpy);
111*9880d681SAndroid Build Coastguard Worker   bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
112*9880d681SAndroid Build Coastguard Worker                          bool ForMemset);
113*9880d681SAndroid Build Coastguard Worker   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
114*9880d681SAndroid Build Coastguard Worker 
115*9880d681SAndroid Build Coastguard Worker   bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
116*9880d681SAndroid Build Coastguard Worker                                unsigned StoreAlignment, Value *StoredVal,
117*9880d681SAndroid Build Coastguard Worker                                Instruction *TheStore,
118*9880d681SAndroid Build Coastguard Worker                                SmallPtrSetImpl<Instruction *> &Stores,
119*9880d681SAndroid Build Coastguard Worker                                const SCEVAddRecExpr *Ev, const SCEV *BECount,
120*9880d681SAndroid Build Coastguard Worker                                bool NegStride);
121*9880d681SAndroid Build Coastguard Worker   bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
122*9880d681SAndroid Build Coastguard Worker 
123*9880d681SAndroid Build Coastguard Worker   /// @}
124*9880d681SAndroid Build Coastguard Worker   /// \name Noncountable Loop Idiom Handling
125*9880d681SAndroid Build Coastguard Worker   /// @{
126*9880d681SAndroid Build Coastguard Worker 
127*9880d681SAndroid Build Coastguard Worker   bool runOnNoncountableLoop();
128*9880d681SAndroid Build Coastguard Worker 
129*9880d681SAndroid Build Coastguard Worker   bool recognizePopcount();
130*9880d681SAndroid Build Coastguard Worker   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
131*9880d681SAndroid Build Coastguard Worker                                PHINode *CntPhi, Value *Var);
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker   /// @}
134*9880d681SAndroid Build Coastguard Worker };
135*9880d681SAndroid Build Coastguard Worker 
136*9880d681SAndroid Build Coastguard Worker class LoopIdiomRecognizeLegacyPass : public LoopPass {
137*9880d681SAndroid Build Coastguard Worker public:
138*9880d681SAndroid Build Coastguard Worker   static char ID;
LoopIdiomRecognizeLegacyPass()139*9880d681SAndroid Build Coastguard Worker   explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
140*9880d681SAndroid Build Coastguard Worker     initializeLoopIdiomRecognizeLegacyPassPass(
141*9880d681SAndroid Build Coastguard Worker         *PassRegistry::getPassRegistry());
142*9880d681SAndroid Build Coastguard Worker   }
143*9880d681SAndroid Build Coastguard Worker 
runOnLoop(Loop * L,LPPassManager & LPM)144*9880d681SAndroid Build Coastguard Worker   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
145*9880d681SAndroid Build Coastguard Worker     if (skipLoop(L))
146*9880d681SAndroid Build Coastguard Worker       return false;
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker     AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
149*9880d681SAndroid Build Coastguard Worker     DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
150*9880d681SAndroid Build Coastguard Worker     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
151*9880d681SAndroid Build Coastguard Worker     ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
152*9880d681SAndroid Build Coastguard Worker     TargetLibraryInfo *TLI =
153*9880d681SAndroid Build Coastguard Worker         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
154*9880d681SAndroid Build Coastguard Worker     const TargetTransformInfo *TTI =
155*9880d681SAndroid Build Coastguard Worker         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
156*9880d681SAndroid Build Coastguard Worker             *L->getHeader()->getParent());
157*9880d681SAndroid Build Coastguard Worker     const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker     LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
160*9880d681SAndroid Build Coastguard Worker     return LIR.runOnLoop(L);
161*9880d681SAndroid Build Coastguard Worker   }
162*9880d681SAndroid Build Coastguard Worker 
163*9880d681SAndroid Build Coastguard Worker   /// This transformation requires natural loop information & requires that
164*9880d681SAndroid Build Coastguard Worker   /// loop preheaders be inserted into the CFG.
165*9880d681SAndroid Build Coastguard Worker   ///
getAnalysisUsage(AnalysisUsage & AU) const166*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
167*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetLibraryInfoWrapperPass>();
168*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetTransformInfoWrapperPass>();
169*9880d681SAndroid Build Coastguard Worker     getLoopAnalysisUsage(AU);
170*9880d681SAndroid Build Coastguard Worker   }
171*9880d681SAndroid Build Coastguard Worker };
172*9880d681SAndroid Build Coastguard Worker } // End anonymous namespace.
173*9880d681SAndroid Build Coastguard Worker 
run(Loop & L,AnalysisManager<Loop> & AM)174*9880d681SAndroid Build Coastguard Worker PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L,
175*9880d681SAndroid Build Coastguard Worker                                               AnalysisManager<Loop> &AM) {
176*9880d681SAndroid Build Coastguard Worker   const auto &FAM =
177*9880d681SAndroid Build Coastguard Worker       AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
178*9880d681SAndroid Build Coastguard Worker   Function *F = L.getHeader()->getParent();
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker   // Use getCachedResult because Loop pass cannot trigger a function analysis.
181*9880d681SAndroid Build Coastguard Worker   auto *AA = FAM.getCachedResult<AAManager>(*F);
182*9880d681SAndroid Build Coastguard Worker   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
183*9880d681SAndroid Build Coastguard Worker   auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
184*9880d681SAndroid Build Coastguard Worker   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
185*9880d681SAndroid Build Coastguard Worker   auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
186*9880d681SAndroid Build Coastguard Worker   const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
187*9880d681SAndroid Build Coastguard Worker   const auto *DL = &L.getHeader()->getModule()->getDataLayout();
188*9880d681SAndroid Build Coastguard Worker   assert((AA && DT && LI && SE && TLI && TTI && DL) &&
189*9880d681SAndroid Build Coastguard Worker          "Analyses for Loop Idiom Recognition not available");
190*9880d681SAndroid Build Coastguard Worker 
191*9880d681SAndroid Build Coastguard Worker   LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
192*9880d681SAndroid Build Coastguard Worker   if (!LIR.runOnLoop(&L))
193*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker   return getLoopPassPreservedAnalyses();
196*9880d681SAndroid Build Coastguard Worker }
197*9880d681SAndroid Build Coastguard Worker 
198*9880d681SAndroid Build Coastguard Worker char LoopIdiomRecognizeLegacyPass::ID = 0;
199*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
200*9880d681SAndroid Build Coastguard Worker                       "Recognize loop idioms", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)201*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopPass)
202*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
203*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
204*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
205*9880d681SAndroid Build Coastguard Worker                     "Recognize loop idioms", false, false)
206*9880d681SAndroid Build Coastguard Worker 
207*9880d681SAndroid Build Coastguard Worker Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
208*9880d681SAndroid Build Coastguard Worker 
deleteDeadInstruction(Instruction * I)209*9880d681SAndroid Build Coastguard Worker static void deleteDeadInstruction(Instruction *I) {
210*9880d681SAndroid Build Coastguard Worker   I->replaceAllUsesWith(UndefValue::get(I->getType()));
211*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
212*9880d681SAndroid Build Coastguard Worker }
213*9880d681SAndroid Build Coastguard Worker 
214*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
215*9880d681SAndroid Build Coastguard Worker //
216*9880d681SAndroid Build Coastguard Worker //          Implementation of LoopIdiomRecognize
217*9880d681SAndroid Build Coastguard Worker //
218*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
219*9880d681SAndroid Build Coastguard Worker 
runOnLoop(Loop * L)220*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::runOnLoop(Loop *L) {
221*9880d681SAndroid Build Coastguard Worker   CurLoop = L;
222*9880d681SAndroid Build Coastguard Worker   // If the loop could not be converted to canonical form, it must have an
223*9880d681SAndroid Build Coastguard Worker   // indirectbr in it, just give up.
224*9880d681SAndroid Build Coastguard Worker   if (!L->getLoopPreheader())
225*9880d681SAndroid Build Coastguard Worker     return false;
226*9880d681SAndroid Build Coastguard Worker 
227*9880d681SAndroid Build Coastguard Worker   // Disable loop idiom recognition if the function's name is a common idiom.
228*9880d681SAndroid Build Coastguard Worker   StringRef Name = L->getHeader()->getParent()->getName();
229*9880d681SAndroid Build Coastguard Worker   if (Name == "memset" || Name == "memcpy")
230*9880d681SAndroid Build Coastguard Worker     return false;
231*9880d681SAndroid Build Coastguard Worker 
232*9880d681SAndroid Build Coastguard Worker   HasMemset = TLI->has(LibFunc::memset);
233*9880d681SAndroid Build Coastguard Worker   HasMemsetPattern = TLI->has(LibFunc::memset_pattern16);
234*9880d681SAndroid Build Coastguard Worker   HasMemcpy = TLI->has(LibFunc::memcpy);
235*9880d681SAndroid Build Coastguard Worker 
236*9880d681SAndroid Build Coastguard Worker   if (HasMemset || HasMemsetPattern || HasMemcpy)
237*9880d681SAndroid Build Coastguard Worker     if (SE->hasLoopInvariantBackedgeTakenCount(L))
238*9880d681SAndroid Build Coastguard Worker       return runOnCountableLoop();
239*9880d681SAndroid Build Coastguard Worker 
240*9880d681SAndroid Build Coastguard Worker   return runOnNoncountableLoop();
241*9880d681SAndroid Build Coastguard Worker }
242*9880d681SAndroid Build Coastguard Worker 
runOnCountableLoop()243*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::runOnCountableLoop() {
244*9880d681SAndroid Build Coastguard Worker   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
245*9880d681SAndroid Build Coastguard Worker   assert(!isa<SCEVCouldNotCompute>(BECount) &&
246*9880d681SAndroid Build Coastguard Worker          "runOnCountableLoop() called on a loop without a predictable"
247*9880d681SAndroid Build Coastguard Worker          "backedge-taken count");
248*9880d681SAndroid Build Coastguard Worker 
249*9880d681SAndroid Build Coastguard Worker   // If this loop executes exactly one time, then it should be peeled, not
250*9880d681SAndroid Build Coastguard Worker   // optimized by this pass.
251*9880d681SAndroid Build Coastguard Worker   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
252*9880d681SAndroid Build Coastguard Worker     if (BECst->getAPInt() == 0)
253*9880d681SAndroid Build Coastguard Worker       return false;
254*9880d681SAndroid Build Coastguard Worker 
255*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock *, 8> ExitBlocks;
256*9880d681SAndroid Build Coastguard Worker   CurLoop->getUniqueExitBlocks(ExitBlocks);
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "loop-idiom Scanning: F["
259*9880d681SAndroid Build Coastguard Worker                << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
260*9880d681SAndroid Build Coastguard Worker                << CurLoop->getHeader()->getName() << "\n");
261*9880d681SAndroid Build Coastguard Worker 
262*9880d681SAndroid Build Coastguard Worker   bool MadeChange = false;
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker   // The following transforms hoist stores/memsets into the loop pre-header.
265*9880d681SAndroid Build Coastguard Worker   // Give up if the loop has instructions may throw.
266*9880d681SAndroid Build Coastguard Worker   LoopSafetyInfo SafetyInfo;
267*9880d681SAndroid Build Coastguard Worker   computeLoopSafetyInfo(&SafetyInfo, CurLoop);
268*9880d681SAndroid Build Coastguard Worker   if (SafetyInfo.MayThrow)
269*9880d681SAndroid Build Coastguard Worker     return MadeChange;
270*9880d681SAndroid Build Coastguard Worker 
271*9880d681SAndroid Build Coastguard Worker   // Scan all the blocks in the loop that are not in subloops.
272*9880d681SAndroid Build Coastguard Worker   for (auto *BB : CurLoop->getBlocks()) {
273*9880d681SAndroid Build Coastguard Worker     // Ignore blocks in subloops.
274*9880d681SAndroid Build Coastguard Worker     if (LI->getLoopFor(BB) != CurLoop)
275*9880d681SAndroid Build Coastguard Worker       continue;
276*9880d681SAndroid Build Coastguard Worker 
277*9880d681SAndroid Build Coastguard Worker     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
278*9880d681SAndroid Build Coastguard Worker   }
279*9880d681SAndroid Build Coastguard Worker   return MadeChange;
280*9880d681SAndroid Build Coastguard Worker }
281*9880d681SAndroid Build Coastguard Worker 
getStoreSizeInBytes(StoreInst * SI,const DataLayout * DL)282*9880d681SAndroid Build Coastguard Worker static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
283*9880d681SAndroid Build Coastguard Worker   uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
284*9880d681SAndroid Build Coastguard Worker   assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
285*9880d681SAndroid Build Coastguard Worker          "Don't overflow unsigned.");
286*9880d681SAndroid Build Coastguard Worker   return (unsigned)SizeInBits >> 3;
287*9880d681SAndroid Build Coastguard Worker }
288*9880d681SAndroid Build Coastguard Worker 
getStoreStride(const SCEVAddRecExpr * StoreEv)289*9880d681SAndroid Build Coastguard Worker static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
290*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
291*9880d681SAndroid Build Coastguard Worker   return ConstStride->getAPInt();
292*9880d681SAndroid Build Coastguard Worker }
293*9880d681SAndroid Build Coastguard Worker 
294*9880d681SAndroid Build Coastguard Worker /// getMemSetPatternValue - If a strided store of the specified value is safe to
295*9880d681SAndroid Build Coastguard Worker /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
296*9880d681SAndroid Build Coastguard Worker /// be passed in.  Otherwise, return null.
297*9880d681SAndroid Build Coastguard Worker ///
298*9880d681SAndroid Build Coastguard Worker /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
299*9880d681SAndroid Build Coastguard Worker /// just replicate their input array and then pass on to memset_pattern16.
getMemSetPatternValue(Value * V,const DataLayout * DL)300*9880d681SAndroid Build Coastguard Worker static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
301*9880d681SAndroid Build Coastguard Worker   // If the value isn't a constant, we can't promote it to being in a constant
302*9880d681SAndroid Build Coastguard Worker   // array.  We could theoretically do a store to an alloca or something, but
303*9880d681SAndroid Build Coastguard Worker   // that doesn't seem worthwhile.
304*9880d681SAndroid Build Coastguard Worker   Constant *C = dyn_cast<Constant>(V);
305*9880d681SAndroid Build Coastguard Worker   if (!C)
306*9880d681SAndroid Build Coastguard Worker     return nullptr;
307*9880d681SAndroid Build Coastguard Worker 
308*9880d681SAndroid Build Coastguard Worker   // Only handle simple values that are a power of two bytes in size.
309*9880d681SAndroid Build Coastguard Worker   uint64_t Size = DL->getTypeSizeInBits(V->getType());
310*9880d681SAndroid Build Coastguard Worker   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
311*9880d681SAndroid Build Coastguard Worker     return nullptr;
312*9880d681SAndroid Build Coastguard Worker 
313*9880d681SAndroid Build Coastguard Worker   // Don't care enough about darwin/ppc to implement this.
314*9880d681SAndroid Build Coastguard Worker   if (DL->isBigEndian())
315*9880d681SAndroid Build Coastguard Worker     return nullptr;
316*9880d681SAndroid Build Coastguard Worker 
317*9880d681SAndroid Build Coastguard Worker   // Convert to size in bytes.
318*9880d681SAndroid Build Coastguard Worker   Size /= 8;
319*9880d681SAndroid Build Coastguard Worker 
320*9880d681SAndroid Build Coastguard Worker   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
321*9880d681SAndroid Build Coastguard Worker   // if the top and bottom are the same (e.g. for vectors and large integers).
322*9880d681SAndroid Build Coastguard Worker   if (Size > 16)
323*9880d681SAndroid Build Coastguard Worker     return nullptr;
324*9880d681SAndroid Build Coastguard Worker 
325*9880d681SAndroid Build Coastguard Worker   // If the constant is exactly 16 bytes, just use it.
326*9880d681SAndroid Build Coastguard Worker   if (Size == 16)
327*9880d681SAndroid Build Coastguard Worker     return C;
328*9880d681SAndroid Build Coastguard Worker 
329*9880d681SAndroid Build Coastguard Worker   // Otherwise, we'll use an array of the constants.
330*9880d681SAndroid Build Coastguard Worker   unsigned ArraySize = 16 / Size;
331*9880d681SAndroid Build Coastguard Worker   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
332*9880d681SAndroid Build Coastguard Worker   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
333*9880d681SAndroid Build Coastguard Worker }
334*9880d681SAndroid Build Coastguard Worker 
isLegalStore(StoreInst * SI,bool & ForMemset,bool & ForMemsetPattern,bool & ForMemcpy)335*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
336*9880d681SAndroid Build Coastguard Worker                                       bool &ForMemsetPattern, bool &ForMemcpy) {
337*9880d681SAndroid Build Coastguard Worker   // Don't touch volatile stores.
338*9880d681SAndroid Build Coastguard Worker   if (!SI->isSimple())
339*9880d681SAndroid Build Coastguard Worker     return false;
340*9880d681SAndroid Build Coastguard Worker 
341*9880d681SAndroid Build Coastguard Worker   // Avoid merging nontemporal stores.
342*9880d681SAndroid Build Coastguard Worker   if (SI->getMetadata(LLVMContext::MD_nontemporal))
343*9880d681SAndroid Build Coastguard Worker     return false;
344*9880d681SAndroid Build Coastguard Worker 
345*9880d681SAndroid Build Coastguard Worker   Value *StoredVal = SI->getValueOperand();
346*9880d681SAndroid Build Coastguard Worker   Value *StorePtr = SI->getPointerOperand();
347*9880d681SAndroid Build Coastguard Worker 
348*9880d681SAndroid Build Coastguard Worker   // Reject stores that are so large that they overflow an unsigned.
349*9880d681SAndroid Build Coastguard Worker   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
350*9880d681SAndroid Build Coastguard Worker   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
351*9880d681SAndroid Build Coastguard Worker     return false;
352*9880d681SAndroid Build Coastguard Worker 
353*9880d681SAndroid Build Coastguard Worker   // See if the pointer expression is an AddRec like {base,+,1} on the current
354*9880d681SAndroid Build Coastguard Worker   // loop, which indicates a strided store.  If we have something else, it's a
355*9880d681SAndroid Build Coastguard Worker   // random store we can't handle.
356*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *StoreEv =
357*9880d681SAndroid Build Coastguard Worker       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
358*9880d681SAndroid Build Coastguard Worker   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
359*9880d681SAndroid Build Coastguard Worker     return false;
360*9880d681SAndroid Build Coastguard Worker 
361*9880d681SAndroid Build Coastguard Worker   // Check to see if we have a constant stride.
362*9880d681SAndroid Build Coastguard Worker   if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
363*9880d681SAndroid Build Coastguard Worker     return false;
364*9880d681SAndroid Build Coastguard Worker 
365*9880d681SAndroid Build Coastguard Worker   // See if the store can be turned into a memset.
366*9880d681SAndroid Build Coastguard Worker 
367*9880d681SAndroid Build Coastguard Worker   // If the stored value is a byte-wise value (like i32 -1), then it may be
368*9880d681SAndroid Build Coastguard Worker   // turned into a memset of i8 -1, assuming that all the consecutive bytes
369*9880d681SAndroid Build Coastguard Worker   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
370*9880d681SAndroid Build Coastguard Worker   // but it can be turned into memset_pattern if the target supports it.
371*9880d681SAndroid Build Coastguard Worker   Value *SplatValue = isBytewiseValue(StoredVal);
372*9880d681SAndroid Build Coastguard Worker   Constant *PatternValue = nullptr;
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker   // If we're allowed to form a memset, and the stored value would be
375*9880d681SAndroid Build Coastguard Worker   // acceptable for memset, use it.
376*9880d681SAndroid Build Coastguard Worker   if (HasMemset && SplatValue &&
377*9880d681SAndroid Build Coastguard Worker       // Verify that the stored value is loop invariant.  If not, we can't
378*9880d681SAndroid Build Coastguard Worker       // promote the memset.
379*9880d681SAndroid Build Coastguard Worker       CurLoop->isLoopInvariant(SplatValue)) {
380*9880d681SAndroid Build Coastguard Worker     // It looks like we can use SplatValue.
381*9880d681SAndroid Build Coastguard Worker     ForMemset = true;
382*9880d681SAndroid Build Coastguard Worker     return true;
383*9880d681SAndroid Build Coastguard Worker   } else if (HasMemsetPattern &&
384*9880d681SAndroid Build Coastguard Worker              // Don't create memset_pattern16s with address spaces.
385*9880d681SAndroid Build Coastguard Worker              StorePtr->getType()->getPointerAddressSpace() == 0 &&
386*9880d681SAndroid Build Coastguard Worker              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
387*9880d681SAndroid Build Coastguard Worker     // It looks like we can use PatternValue!
388*9880d681SAndroid Build Coastguard Worker     ForMemsetPattern = true;
389*9880d681SAndroid Build Coastguard Worker     return true;
390*9880d681SAndroid Build Coastguard Worker   }
391*9880d681SAndroid Build Coastguard Worker 
392*9880d681SAndroid Build Coastguard Worker   // Otherwise, see if the store can be turned into a memcpy.
393*9880d681SAndroid Build Coastguard Worker   if (HasMemcpy) {
394*9880d681SAndroid Build Coastguard Worker     // Check to see if the stride matches the size of the store.  If so, then we
395*9880d681SAndroid Build Coastguard Worker     // know that every byte is touched in the loop.
396*9880d681SAndroid Build Coastguard Worker     APInt Stride = getStoreStride(StoreEv);
397*9880d681SAndroid Build Coastguard Worker     unsigned StoreSize = getStoreSizeInBytes(SI, DL);
398*9880d681SAndroid Build Coastguard Worker     if (StoreSize != Stride && StoreSize != -Stride)
399*9880d681SAndroid Build Coastguard Worker       return false;
400*9880d681SAndroid Build Coastguard Worker 
401*9880d681SAndroid Build Coastguard Worker     // The store must be feeding a non-volatile load.
402*9880d681SAndroid Build Coastguard Worker     LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
403*9880d681SAndroid Build Coastguard Worker     if (!LI || !LI->isSimple())
404*9880d681SAndroid Build Coastguard Worker       return false;
405*9880d681SAndroid Build Coastguard Worker 
406*9880d681SAndroid Build Coastguard Worker     // See if the pointer expression is an AddRec like {base,+,1} on the current
407*9880d681SAndroid Build Coastguard Worker     // loop, which indicates a strided load.  If we have something else, it's a
408*9880d681SAndroid Build Coastguard Worker     // random load we can't handle.
409*9880d681SAndroid Build Coastguard Worker     const SCEVAddRecExpr *LoadEv =
410*9880d681SAndroid Build Coastguard Worker         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
411*9880d681SAndroid Build Coastguard Worker     if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
412*9880d681SAndroid Build Coastguard Worker       return false;
413*9880d681SAndroid Build Coastguard Worker 
414*9880d681SAndroid Build Coastguard Worker     // The store and load must share the same stride.
415*9880d681SAndroid Build Coastguard Worker     if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
416*9880d681SAndroid Build Coastguard Worker       return false;
417*9880d681SAndroid Build Coastguard Worker 
418*9880d681SAndroid Build Coastguard Worker     // Success.  This store can be converted into a memcpy.
419*9880d681SAndroid Build Coastguard Worker     ForMemcpy = true;
420*9880d681SAndroid Build Coastguard Worker     return true;
421*9880d681SAndroid Build Coastguard Worker   }
422*9880d681SAndroid Build Coastguard Worker   // This store can't be transformed into a memset/memcpy.
423*9880d681SAndroid Build Coastguard Worker   return false;
424*9880d681SAndroid Build Coastguard Worker }
425*9880d681SAndroid Build Coastguard Worker 
collectStores(BasicBlock * BB)426*9880d681SAndroid Build Coastguard Worker void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
427*9880d681SAndroid Build Coastguard Worker   StoreRefsForMemset.clear();
428*9880d681SAndroid Build Coastguard Worker   StoreRefsForMemsetPattern.clear();
429*9880d681SAndroid Build Coastguard Worker   StoreRefsForMemcpy.clear();
430*9880d681SAndroid Build Coastguard Worker   for (Instruction &I : *BB) {
431*9880d681SAndroid Build Coastguard Worker     StoreInst *SI = dyn_cast<StoreInst>(&I);
432*9880d681SAndroid Build Coastguard Worker     if (!SI)
433*9880d681SAndroid Build Coastguard Worker       continue;
434*9880d681SAndroid Build Coastguard Worker 
435*9880d681SAndroid Build Coastguard Worker     bool ForMemset = false;
436*9880d681SAndroid Build Coastguard Worker     bool ForMemsetPattern = false;
437*9880d681SAndroid Build Coastguard Worker     bool ForMemcpy = false;
438*9880d681SAndroid Build Coastguard Worker     // Make sure this is a strided store with a constant stride.
439*9880d681SAndroid Build Coastguard Worker     if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy))
440*9880d681SAndroid Build Coastguard Worker       continue;
441*9880d681SAndroid Build Coastguard Worker 
442*9880d681SAndroid Build Coastguard Worker     // Save the store locations.
443*9880d681SAndroid Build Coastguard Worker     if (ForMemset) {
444*9880d681SAndroid Build Coastguard Worker       // Find the base pointer.
445*9880d681SAndroid Build Coastguard Worker       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
446*9880d681SAndroid Build Coastguard Worker       StoreRefsForMemset[Ptr].push_back(SI);
447*9880d681SAndroid Build Coastguard Worker     } else if (ForMemsetPattern) {
448*9880d681SAndroid Build Coastguard Worker       // Find the base pointer.
449*9880d681SAndroid Build Coastguard Worker       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
450*9880d681SAndroid Build Coastguard Worker       StoreRefsForMemsetPattern[Ptr].push_back(SI);
451*9880d681SAndroid Build Coastguard Worker     } else if (ForMemcpy)
452*9880d681SAndroid Build Coastguard Worker       StoreRefsForMemcpy.push_back(SI);
453*9880d681SAndroid Build Coastguard Worker   }
454*9880d681SAndroid Build Coastguard Worker }
455*9880d681SAndroid Build Coastguard Worker 
456*9880d681SAndroid Build Coastguard Worker /// runOnLoopBlock - Process the specified block, which lives in a counted loop
457*9880d681SAndroid Build Coastguard Worker /// with the specified backedge count.  This block is known to be in the current
458*9880d681SAndroid Build Coastguard Worker /// loop and not in any subloops.
runOnLoopBlock(BasicBlock * BB,const SCEV * BECount,SmallVectorImpl<BasicBlock * > & ExitBlocks)459*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::runOnLoopBlock(
460*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB, const SCEV *BECount,
461*9880d681SAndroid Build Coastguard Worker     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
462*9880d681SAndroid Build Coastguard Worker   // We can only promote stores in this block if they are unconditionally
463*9880d681SAndroid Build Coastguard Worker   // executed in the loop.  For a block to be unconditionally executed, it has
464*9880d681SAndroid Build Coastguard Worker   // to dominate all the exit blocks of the loop.  Verify this now.
465*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
466*9880d681SAndroid Build Coastguard Worker     if (!DT->dominates(BB, ExitBlocks[i]))
467*9880d681SAndroid Build Coastguard Worker       return false;
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   bool MadeChange = false;
470*9880d681SAndroid Build Coastguard Worker   // Look for store instructions, which may be optimized to memset/memcpy.
471*9880d681SAndroid Build Coastguard Worker   collectStores(BB);
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker   // Look for a single store or sets of stores with a common base, which can be
474*9880d681SAndroid Build Coastguard Worker   // optimized into a memset (memset_pattern).  The latter most commonly happens
475*9880d681SAndroid Build Coastguard Worker   // with structs and handunrolled loops.
476*9880d681SAndroid Build Coastguard Worker   for (auto &SL : StoreRefsForMemset)
477*9880d681SAndroid Build Coastguard Worker     MadeChange |= processLoopStores(SL.second, BECount, true);
478*9880d681SAndroid Build Coastguard Worker 
479*9880d681SAndroid Build Coastguard Worker   for (auto &SL : StoreRefsForMemsetPattern)
480*9880d681SAndroid Build Coastguard Worker     MadeChange |= processLoopStores(SL.second, BECount, false);
481*9880d681SAndroid Build Coastguard Worker 
482*9880d681SAndroid Build Coastguard Worker   // Optimize the store into a memcpy, if it feeds an similarly strided load.
483*9880d681SAndroid Build Coastguard Worker   for (auto &SI : StoreRefsForMemcpy)
484*9880d681SAndroid Build Coastguard Worker     MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
485*9880d681SAndroid Build Coastguard Worker 
486*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
487*9880d681SAndroid Build Coastguard Worker     Instruction *Inst = &*I++;
488*9880d681SAndroid Build Coastguard Worker     // Look for memset instructions, which may be optimized to a larger memset.
489*9880d681SAndroid Build Coastguard Worker     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
490*9880d681SAndroid Build Coastguard Worker       WeakVH InstPtr(&*I);
491*9880d681SAndroid Build Coastguard Worker       if (!processLoopMemSet(MSI, BECount))
492*9880d681SAndroid Build Coastguard Worker         continue;
493*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
494*9880d681SAndroid Build Coastguard Worker 
495*9880d681SAndroid Build Coastguard Worker       // If processing the memset invalidated our iterator, start over from the
496*9880d681SAndroid Build Coastguard Worker       // top of the block.
497*9880d681SAndroid Build Coastguard Worker       if (!InstPtr)
498*9880d681SAndroid Build Coastguard Worker         I = BB->begin();
499*9880d681SAndroid Build Coastguard Worker       continue;
500*9880d681SAndroid Build Coastguard Worker     }
501*9880d681SAndroid Build Coastguard Worker   }
502*9880d681SAndroid Build Coastguard Worker 
503*9880d681SAndroid Build Coastguard Worker   return MadeChange;
504*9880d681SAndroid Build Coastguard Worker }
505*9880d681SAndroid Build Coastguard Worker 
506*9880d681SAndroid Build Coastguard Worker /// processLoopStores - See if this store(s) can be promoted to a memset.
processLoopStores(SmallVectorImpl<StoreInst * > & SL,const SCEV * BECount,bool ForMemset)507*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
508*9880d681SAndroid Build Coastguard Worker                                            const SCEV *BECount,
509*9880d681SAndroid Build Coastguard Worker                                            bool ForMemset) {
510*9880d681SAndroid Build Coastguard Worker   // Try to find consecutive stores that can be transformed into memsets.
511*9880d681SAndroid Build Coastguard Worker   SetVector<StoreInst *> Heads, Tails;
512*9880d681SAndroid Build Coastguard Worker   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
513*9880d681SAndroid Build Coastguard Worker 
514*9880d681SAndroid Build Coastguard Worker   // Do a quadratic search on all of the given stores and find
515*9880d681SAndroid Build Coastguard Worker   // all of the pairs of stores that follow each other.
516*9880d681SAndroid Build Coastguard Worker   SmallVector<unsigned, 16> IndexQueue;
517*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = SL.size(); i < e; ++i) {
518*9880d681SAndroid Build Coastguard Worker     assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
519*9880d681SAndroid Build Coastguard Worker 
520*9880d681SAndroid Build Coastguard Worker     Value *FirstStoredVal = SL[i]->getValueOperand();
521*9880d681SAndroid Build Coastguard Worker     Value *FirstStorePtr = SL[i]->getPointerOperand();
522*9880d681SAndroid Build Coastguard Worker     const SCEVAddRecExpr *FirstStoreEv =
523*9880d681SAndroid Build Coastguard Worker         cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
524*9880d681SAndroid Build Coastguard Worker     APInt FirstStride = getStoreStride(FirstStoreEv);
525*9880d681SAndroid Build Coastguard Worker     unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
526*9880d681SAndroid Build Coastguard Worker 
527*9880d681SAndroid Build Coastguard Worker     // See if we can optimize just this store in isolation.
528*9880d681SAndroid Build Coastguard Worker     if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
529*9880d681SAndroid Build Coastguard Worker       Heads.insert(SL[i]);
530*9880d681SAndroid Build Coastguard Worker       continue;
531*9880d681SAndroid Build Coastguard Worker     }
532*9880d681SAndroid Build Coastguard Worker 
533*9880d681SAndroid Build Coastguard Worker     Value *FirstSplatValue = nullptr;
534*9880d681SAndroid Build Coastguard Worker     Constant *FirstPatternValue = nullptr;
535*9880d681SAndroid Build Coastguard Worker 
536*9880d681SAndroid Build Coastguard Worker     if (ForMemset)
537*9880d681SAndroid Build Coastguard Worker       FirstSplatValue = isBytewiseValue(FirstStoredVal);
538*9880d681SAndroid Build Coastguard Worker     else
539*9880d681SAndroid Build Coastguard Worker       FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
540*9880d681SAndroid Build Coastguard Worker 
541*9880d681SAndroid Build Coastguard Worker     assert((FirstSplatValue || FirstPatternValue) &&
542*9880d681SAndroid Build Coastguard Worker            "Expected either splat value or pattern value.");
543*9880d681SAndroid Build Coastguard Worker 
544*9880d681SAndroid Build Coastguard Worker     IndexQueue.clear();
545*9880d681SAndroid Build Coastguard Worker     // If a store has multiple consecutive store candidates, search Stores
546*9880d681SAndroid Build Coastguard Worker     // array according to the sequence: from i+1 to e, then from i-1 to 0.
547*9880d681SAndroid Build Coastguard Worker     // This is because usually pairing with immediate succeeding or preceding
548*9880d681SAndroid Build Coastguard Worker     // candidate create the best chance to find memset opportunity.
549*9880d681SAndroid Build Coastguard Worker     unsigned j = 0;
550*9880d681SAndroid Build Coastguard Worker     for (j = i + 1; j < e; ++j)
551*9880d681SAndroid Build Coastguard Worker       IndexQueue.push_back(j);
552*9880d681SAndroid Build Coastguard Worker     for (j = i; j > 0; --j)
553*9880d681SAndroid Build Coastguard Worker       IndexQueue.push_back(j - 1);
554*9880d681SAndroid Build Coastguard Worker 
555*9880d681SAndroid Build Coastguard Worker     for (auto &k : IndexQueue) {
556*9880d681SAndroid Build Coastguard Worker       assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
557*9880d681SAndroid Build Coastguard Worker       Value *SecondStorePtr = SL[k]->getPointerOperand();
558*9880d681SAndroid Build Coastguard Worker       const SCEVAddRecExpr *SecondStoreEv =
559*9880d681SAndroid Build Coastguard Worker           cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
560*9880d681SAndroid Build Coastguard Worker       APInt SecondStride = getStoreStride(SecondStoreEv);
561*9880d681SAndroid Build Coastguard Worker 
562*9880d681SAndroid Build Coastguard Worker       if (FirstStride != SecondStride)
563*9880d681SAndroid Build Coastguard Worker         continue;
564*9880d681SAndroid Build Coastguard Worker 
565*9880d681SAndroid Build Coastguard Worker       Value *SecondStoredVal = SL[k]->getValueOperand();
566*9880d681SAndroid Build Coastguard Worker       Value *SecondSplatValue = nullptr;
567*9880d681SAndroid Build Coastguard Worker       Constant *SecondPatternValue = nullptr;
568*9880d681SAndroid Build Coastguard Worker 
569*9880d681SAndroid Build Coastguard Worker       if (ForMemset)
570*9880d681SAndroid Build Coastguard Worker         SecondSplatValue = isBytewiseValue(SecondStoredVal);
571*9880d681SAndroid Build Coastguard Worker       else
572*9880d681SAndroid Build Coastguard Worker         SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker       assert((SecondSplatValue || SecondPatternValue) &&
575*9880d681SAndroid Build Coastguard Worker              "Expected either splat value or pattern value.");
576*9880d681SAndroid Build Coastguard Worker 
577*9880d681SAndroid Build Coastguard Worker       if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
578*9880d681SAndroid Build Coastguard Worker         if (ForMemset) {
579*9880d681SAndroid Build Coastguard Worker           if (FirstSplatValue != SecondSplatValue)
580*9880d681SAndroid Build Coastguard Worker             continue;
581*9880d681SAndroid Build Coastguard Worker         } else {
582*9880d681SAndroid Build Coastguard Worker           if (FirstPatternValue != SecondPatternValue)
583*9880d681SAndroid Build Coastguard Worker             continue;
584*9880d681SAndroid Build Coastguard Worker         }
585*9880d681SAndroid Build Coastguard Worker         Tails.insert(SL[k]);
586*9880d681SAndroid Build Coastguard Worker         Heads.insert(SL[i]);
587*9880d681SAndroid Build Coastguard Worker         ConsecutiveChain[SL[i]] = SL[k];
588*9880d681SAndroid Build Coastguard Worker         break;
589*9880d681SAndroid Build Coastguard Worker       }
590*9880d681SAndroid Build Coastguard Worker     }
591*9880d681SAndroid Build Coastguard Worker   }
592*9880d681SAndroid Build Coastguard Worker 
593*9880d681SAndroid Build Coastguard Worker   // We may run into multiple chains that merge into a single chain. We mark the
594*9880d681SAndroid Build Coastguard Worker   // stores that we transformed so that we don't visit the same store twice.
595*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value *, 16> TransformedStores;
596*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
597*9880d681SAndroid Build Coastguard Worker 
598*9880d681SAndroid Build Coastguard Worker   // For stores that start but don't end a link in the chain:
599*9880d681SAndroid Build Coastguard Worker   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
600*9880d681SAndroid Build Coastguard Worker        it != e; ++it) {
601*9880d681SAndroid Build Coastguard Worker     if (Tails.count(*it))
602*9880d681SAndroid Build Coastguard Worker       continue;
603*9880d681SAndroid Build Coastguard Worker 
604*9880d681SAndroid Build Coastguard Worker     // We found a store instr that starts a chain. Now follow the chain and try
605*9880d681SAndroid Build Coastguard Worker     // to transform it.
606*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<Instruction *, 8> AdjacentStores;
607*9880d681SAndroid Build Coastguard Worker     StoreInst *I = *it;
608*9880d681SAndroid Build Coastguard Worker 
609*9880d681SAndroid Build Coastguard Worker     StoreInst *HeadStore = I;
610*9880d681SAndroid Build Coastguard Worker     unsigned StoreSize = 0;
611*9880d681SAndroid Build Coastguard Worker 
612*9880d681SAndroid Build Coastguard Worker     // Collect the chain into a list.
613*9880d681SAndroid Build Coastguard Worker     while (Tails.count(I) || Heads.count(I)) {
614*9880d681SAndroid Build Coastguard Worker       if (TransformedStores.count(I))
615*9880d681SAndroid Build Coastguard Worker         break;
616*9880d681SAndroid Build Coastguard Worker       AdjacentStores.insert(I);
617*9880d681SAndroid Build Coastguard Worker 
618*9880d681SAndroid Build Coastguard Worker       StoreSize += getStoreSizeInBytes(I, DL);
619*9880d681SAndroid Build Coastguard Worker       // Move to the next value in the chain.
620*9880d681SAndroid Build Coastguard Worker       I = ConsecutiveChain[I];
621*9880d681SAndroid Build Coastguard Worker     }
622*9880d681SAndroid Build Coastguard Worker 
623*9880d681SAndroid Build Coastguard Worker     Value *StoredVal = HeadStore->getValueOperand();
624*9880d681SAndroid Build Coastguard Worker     Value *StorePtr = HeadStore->getPointerOperand();
625*9880d681SAndroid Build Coastguard Worker     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
626*9880d681SAndroid Build Coastguard Worker     APInt Stride = getStoreStride(StoreEv);
627*9880d681SAndroid Build Coastguard Worker 
628*9880d681SAndroid Build Coastguard Worker     // Check to see if the stride matches the size of the stores.  If so, then
629*9880d681SAndroid Build Coastguard Worker     // we know that every byte is touched in the loop.
630*9880d681SAndroid Build Coastguard Worker     if (StoreSize != Stride && StoreSize != -Stride)
631*9880d681SAndroid Build Coastguard Worker       continue;
632*9880d681SAndroid Build Coastguard Worker 
633*9880d681SAndroid Build Coastguard Worker     bool NegStride = StoreSize == -Stride;
634*9880d681SAndroid Build Coastguard Worker 
635*9880d681SAndroid Build Coastguard Worker     if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
636*9880d681SAndroid Build Coastguard Worker                                 StoredVal, HeadStore, AdjacentStores, StoreEv,
637*9880d681SAndroid Build Coastguard Worker                                 BECount, NegStride)) {
638*9880d681SAndroid Build Coastguard Worker       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
639*9880d681SAndroid Build Coastguard Worker       Changed = true;
640*9880d681SAndroid Build Coastguard Worker     }
641*9880d681SAndroid Build Coastguard Worker   }
642*9880d681SAndroid Build Coastguard Worker 
643*9880d681SAndroid Build Coastguard Worker   return Changed;
644*9880d681SAndroid Build Coastguard Worker }
645*9880d681SAndroid Build Coastguard Worker 
646*9880d681SAndroid Build Coastguard Worker /// processLoopMemSet - See if this memset can be promoted to a large memset.
processLoopMemSet(MemSetInst * MSI,const SCEV * BECount)647*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
648*9880d681SAndroid Build Coastguard Worker                                            const SCEV *BECount) {
649*9880d681SAndroid Build Coastguard Worker   // We can only handle non-volatile memsets with a constant size.
650*9880d681SAndroid Build Coastguard Worker   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
651*9880d681SAndroid Build Coastguard Worker     return false;
652*9880d681SAndroid Build Coastguard Worker 
653*9880d681SAndroid Build Coastguard Worker   // If we're not allowed to hack on memset, we fail.
654*9880d681SAndroid Build Coastguard Worker   if (!HasMemset)
655*9880d681SAndroid Build Coastguard Worker     return false;
656*9880d681SAndroid Build Coastguard Worker 
657*9880d681SAndroid Build Coastguard Worker   Value *Pointer = MSI->getDest();
658*9880d681SAndroid Build Coastguard Worker 
659*9880d681SAndroid Build Coastguard Worker   // See if the pointer expression is an AddRec like {base,+,1} on the current
660*9880d681SAndroid Build Coastguard Worker   // loop, which indicates a strided store.  If we have something else, it's a
661*9880d681SAndroid Build Coastguard Worker   // random store we can't handle.
662*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
663*9880d681SAndroid Build Coastguard Worker   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
664*9880d681SAndroid Build Coastguard Worker     return false;
665*9880d681SAndroid Build Coastguard Worker 
666*9880d681SAndroid Build Coastguard Worker   // Reject memsets that are so large that they overflow an unsigned.
667*9880d681SAndroid Build Coastguard Worker   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
668*9880d681SAndroid Build Coastguard Worker   if ((SizeInBytes >> 32) != 0)
669*9880d681SAndroid Build Coastguard Worker     return false;
670*9880d681SAndroid Build Coastguard Worker 
671*9880d681SAndroid Build Coastguard Worker   // Check to see if the stride matches the size of the memset.  If so, then we
672*9880d681SAndroid Build Coastguard Worker   // know that every byte is touched in the loop.
673*9880d681SAndroid Build Coastguard Worker   const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
674*9880d681SAndroid Build Coastguard Worker   if (!ConstStride)
675*9880d681SAndroid Build Coastguard Worker     return false;
676*9880d681SAndroid Build Coastguard Worker 
677*9880d681SAndroid Build Coastguard Worker   APInt Stride = ConstStride->getAPInt();
678*9880d681SAndroid Build Coastguard Worker   if (SizeInBytes != Stride && SizeInBytes != -Stride)
679*9880d681SAndroid Build Coastguard Worker     return false;
680*9880d681SAndroid Build Coastguard Worker 
681*9880d681SAndroid Build Coastguard Worker   // Verify that the memset value is loop invariant.  If not, we can't promote
682*9880d681SAndroid Build Coastguard Worker   // the memset.
683*9880d681SAndroid Build Coastguard Worker   Value *SplatValue = MSI->getValue();
684*9880d681SAndroid Build Coastguard Worker   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
685*9880d681SAndroid Build Coastguard Worker     return false;
686*9880d681SAndroid Build Coastguard Worker 
687*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Instruction *, 1> MSIs;
688*9880d681SAndroid Build Coastguard Worker   MSIs.insert(MSI);
689*9880d681SAndroid Build Coastguard Worker   bool NegStride = SizeInBytes == -Stride;
690*9880d681SAndroid Build Coastguard Worker   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
691*9880d681SAndroid Build Coastguard Worker                                  MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
692*9880d681SAndroid Build Coastguard Worker                                  BECount, NegStride);
693*9880d681SAndroid Build Coastguard Worker }
694*9880d681SAndroid Build Coastguard Worker 
695*9880d681SAndroid Build Coastguard Worker /// mayLoopAccessLocation - Return true if the specified loop might access the
696*9880d681SAndroid Build Coastguard Worker /// specified pointer location, which is a loop-strided access.  The 'Access'
697*9880d681SAndroid Build Coastguard Worker /// argument specifies what the verboten forms of access are (read or write).
698*9880d681SAndroid Build Coastguard Worker static bool
mayLoopAccessLocation(Value * Ptr,ModRefInfo Access,Loop * L,const SCEV * BECount,unsigned StoreSize,AliasAnalysis & AA,SmallPtrSetImpl<Instruction * > & IgnoredStores)699*9880d681SAndroid Build Coastguard Worker mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
700*9880d681SAndroid Build Coastguard Worker                       const SCEV *BECount, unsigned StoreSize,
701*9880d681SAndroid Build Coastguard Worker                       AliasAnalysis &AA,
702*9880d681SAndroid Build Coastguard Worker                       SmallPtrSetImpl<Instruction *> &IgnoredStores) {
703*9880d681SAndroid Build Coastguard Worker   // Get the location that may be stored across the loop.  Since the access is
704*9880d681SAndroid Build Coastguard Worker   // strided positively through memory, we say that the modified location starts
705*9880d681SAndroid Build Coastguard Worker   // at the pointer and has infinite size.
706*9880d681SAndroid Build Coastguard Worker   uint64_t AccessSize = MemoryLocation::UnknownSize;
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker   // If the loop iterates a fixed number of times, we can refine the access size
709*9880d681SAndroid Build Coastguard Worker   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
710*9880d681SAndroid Build Coastguard Worker   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
711*9880d681SAndroid Build Coastguard Worker     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
712*9880d681SAndroid Build Coastguard Worker 
713*9880d681SAndroid Build Coastguard Worker   // TODO: For this to be really effective, we have to dive into the pointer
714*9880d681SAndroid Build Coastguard Worker   // operand in the store.  Store to &A[i] of 100 will always return may alias
715*9880d681SAndroid Build Coastguard Worker   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
716*9880d681SAndroid Build Coastguard Worker   // which will then no-alias a store to &A[100].
717*9880d681SAndroid Build Coastguard Worker   MemoryLocation StoreLoc(Ptr, AccessSize);
718*9880d681SAndroid Build Coastguard Worker 
719*9880d681SAndroid Build Coastguard Worker   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
720*9880d681SAndroid Build Coastguard Worker        ++BI)
721*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : **BI)
722*9880d681SAndroid Build Coastguard Worker       if (IgnoredStores.count(&I) == 0 &&
723*9880d681SAndroid Build Coastguard Worker           (AA.getModRefInfo(&I, StoreLoc) & Access))
724*9880d681SAndroid Build Coastguard Worker         return true;
725*9880d681SAndroid Build Coastguard Worker 
726*9880d681SAndroid Build Coastguard Worker   return false;
727*9880d681SAndroid Build Coastguard Worker }
728*9880d681SAndroid Build Coastguard Worker 
729*9880d681SAndroid Build Coastguard Worker // If we have a negative stride, Start refers to the end of the memory location
730*9880d681SAndroid Build Coastguard Worker // we're trying to memset.  Therefore, we need to recompute the base pointer,
731*9880d681SAndroid Build Coastguard Worker // which is just Start - BECount*Size.
getStartForNegStride(const SCEV * Start,const SCEV * BECount,Type * IntPtr,unsigned StoreSize,ScalarEvolution * SE)732*9880d681SAndroid Build Coastguard Worker static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
733*9880d681SAndroid Build Coastguard Worker                                         Type *IntPtr, unsigned StoreSize,
734*9880d681SAndroid Build Coastguard Worker                                         ScalarEvolution *SE) {
735*9880d681SAndroid Build Coastguard Worker   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
736*9880d681SAndroid Build Coastguard Worker   if (StoreSize != 1)
737*9880d681SAndroid Build Coastguard Worker     Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
738*9880d681SAndroid Build Coastguard Worker                            SCEV::FlagNUW);
739*9880d681SAndroid Build Coastguard Worker   return SE->getMinusSCEV(Start, Index);
740*9880d681SAndroid Build Coastguard Worker }
741*9880d681SAndroid Build Coastguard Worker 
742*9880d681SAndroid Build Coastguard Worker /// processLoopStridedStore - We see a strided store of some value.  If we can
743*9880d681SAndroid Build Coastguard Worker /// transform this into a memset or memset_pattern in the loop preheader, do so.
processLoopStridedStore(Value * DestPtr,unsigned StoreSize,unsigned StoreAlignment,Value * StoredVal,Instruction * TheStore,SmallPtrSetImpl<Instruction * > & Stores,const SCEVAddRecExpr * Ev,const SCEV * BECount,bool NegStride)744*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::processLoopStridedStore(
745*9880d681SAndroid Build Coastguard Worker     Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
746*9880d681SAndroid Build Coastguard Worker     Value *StoredVal, Instruction *TheStore,
747*9880d681SAndroid Build Coastguard Worker     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
748*9880d681SAndroid Build Coastguard Worker     const SCEV *BECount, bool NegStride) {
749*9880d681SAndroid Build Coastguard Worker   Value *SplatValue = isBytewiseValue(StoredVal);
750*9880d681SAndroid Build Coastguard Worker   Constant *PatternValue = nullptr;
751*9880d681SAndroid Build Coastguard Worker 
752*9880d681SAndroid Build Coastguard Worker   if (!SplatValue)
753*9880d681SAndroid Build Coastguard Worker     PatternValue = getMemSetPatternValue(StoredVal, DL);
754*9880d681SAndroid Build Coastguard Worker 
755*9880d681SAndroid Build Coastguard Worker   assert((SplatValue || PatternValue) &&
756*9880d681SAndroid Build Coastguard Worker          "Expected either splat value or pattern value.");
757*9880d681SAndroid Build Coastguard Worker 
758*9880d681SAndroid Build Coastguard Worker   // The trip count of the loop and the base pointer of the addrec SCEV is
759*9880d681SAndroid Build Coastguard Worker   // guaranteed to be loop invariant, which means that it should dominate the
760*9880d681SAndroid Build Coastguard Worker   // header.  This allows us to insert code for it in the preheader.
761*9880d681SAndroid Build Coastguard Worker   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
762*9880d681SAndroid Build Coastguard Worker   BasicBlock *Preheader = CurLoop->getLoopPreheader();
763*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(Preheader->getTerminator());
764*9880d681SAndroid Build Coastguard Worker   SCEVExpander Expander(*SE, *DL, "loop-idiom");
765*9880d681SAndroid Build Coastguard Worker 
766*9880d681SAndroid Build Coastguard Worker   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
767*9880d681SAndroid Build Coastguard Worker   Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
768*9880d681SAndroid Build Coastguard Worker 
769*9880d681SAndroid Build Coastguard Worker   const SCEV *Start = Ev->getStart();
770*9880d681SAndroid Build Coastguard Worker   // Handle negative strided loops.
771*9880d681SAndroid Build Coastguard Worker   if (NegStride)
772*9880d681SAndroid Build Coastguard Worker     Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
773*9880d681SAndroid Build Coastguard Worker 
774*9880d681SAndroid Build Coastguard Worker   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
775*9880d681SAndroid Build Coastguard Worker   // this into a memset in the loop preheader now if we want.  However, this
776*9880d681SAndroid Build Coastguard Worker   // would be unsafe to do if there is anything else in the loop that may read
777*9880d681SAndroid Build Coastguard Worker   // or write to the aliased location.  Check for any overlap by generating the
778*9880d681SAndroid Build Coastguard Worker   // base pointer and checking the region.
779*9880d681SAndroid Build Coastguard Worker   Value *BasePtr =
780*9880d681SAndroid Build Coastguard Worker       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
781*9880d681SAndroid Build Coastguard Worker   if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
782*9880d681SAndroid Build Coastguard Worker                             *AA, Stores)) {
783*9880d681SAndroid Build Coastguard Worker     Expander.clear();
784*9880d681SAndroid Build Coastguard Worker     // If we generated new code for the base pointer, clean up.
785*9880d681SAndroid Build Coastguard Worker     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
786*9880d681SAndroid Build Coastguard Worker     return false;
787*9880d681SAndroid Build Coastguard Worker   }
788*9880d681SAndroid Build Coastguard Worker 
789*9880d681SAndroid Build Coastguard Worker   // Okay, everything looks good, insert the memset.
790*9880d681SAndroid Build Coastguard Worker 
791*9880d681SAndroid Build Coastguard Worker   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
792*9880d681SAndroid Build Coastguard Worker   // pointer size if it isn't already.
793*9880d681SAndroid Build Coastguard Worker   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
794*9880d681SAndroid Build Coastguard Worker 
795*9880d681SAndroid Build Coastguard Worker   const SCEV *NumBytesS =
796*9880d681SAndroid Build Coastguard Worker       SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
797*9880d681SAndroid Build Coastguard Worker   if (StoreSize != 1) {
798*9880d681SAndroid Build Coastguard Worker     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
799*9880d681SAndroid Build Coastguard Worker                                SCEV::FlagNUW);
800*9880d681SAndroid Build Coastguard Worker   }
801*9880d681SAndroid Build Coastguard Worker 
802*9880d681SAndroid Build Coastguard Worker   Value *NumBytes =
803*9880d681SAndroid Build Coastguard Worker       Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
804*9880d681SAndroid Build Coastguard Worker 
805*9880d681SAndroid Build Coastguard Worker   CallInst *NewCall;
806*9880d681SAndroid Build Coastguard Worker   if (SplatValue) {
807*9880d681SAndroid Build Coastguard Worker     NewCall =
808*9880d681SAndroid Build Coastguard Worker         Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
809*9880d681SAndroid Build Coastguard Worker   } else {
810*9880d681SAndroid Build Coastguard Worker     // Everything is emitted in default address space
811*9880d681SAndroid Build Coastguard Worker     Type *Int8PtrTy = DestInt8PtrTy;
812*9880d681SAndroid Build Coastguard Worker 
813*9880d681SAndroid Build Coastguard Worker     Module *M = TheStore->getModule();
814*9880d681SAndroid Build Coastguard Worker     Value *MSP =
815*9880d681SAndroid Build Coastguard Worker         M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
816*9880d681SAndroid Build Coastguard Worker                                Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
817*9880d681SAndroid Build Coastguard Worker     inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
818*9880d681SAndroid Build Coastguard Worker 
819*9880d681SAndroid Build Coastguard Worker     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
820*9880d681SAndroid Build Coastguard Worker     // an constant array of 16-bytes.  Plop the value into a mergable global.
821*9880d681SAndroid Build Coastguard Worker     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
822*9880d681SAndroid Build Coastguard Worker                                             GlobalValue::PrivateLinkage,
823*9880d681SAndroid Build Coastguard Worker                                             PatternValue, ".memset_pattern");
824*9880d681SAndroid Build Coastguard Worker     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
825*9880d681SAndroid Build Coastguard Worker     GV->setAlignment(16);
826*9880d681SAndroid Build Coastguard Worker     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
827*9880d681SAndroid Build Coastguard Worker     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
828*9880d681SAndroid Build Coastguard Worker   }
829*9880d681SAndroid Build Coastguard Worker 
830*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
831*9880d681SAndroid Build Coastguard Worker                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
832*9880d681SAndroid Build Coastguard Worker   NewCall->setDebugLoc(TheStore->getDebugLoc());
833*9880d681SAndroid Build Coastguard Worker 
834*9880d681SAndroid Build Coastguard Worker   // Okay, the memset has been formed.  Zap the original store and anything that
835*9880d681SAndroid Build Coastguard Worker   // feeds into it.
836*9880d681SAndroid Build Coastguard Worker   for (auto *I : Stores)
837*9880d681SAndroid Build Coastguard Worker     deleteDeadInstruction(I);
838*9880d681SAndroid Build Coastguard Worker   ++NumMemSet;
839*9880d681SAndroid Build Coastguard Worker   return true;
840*9880d681SAndroid Build Coastguard Worker }
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker /// If the stored value is a strided load in the same loop with the same stride
843*9880d681SAndroid Build Coastguard Worker /// this may be transformable into a memcpy.  This kicks in for stuff like
844*9880d681SAndroid Build Coastguard Worker ///   for (i) A[i] = B[i];
processLoopStoreOfLoopLoad(StoreInst * SI,const SCEV * BECount)845*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
846*9880d681SAndroid Build Coastguard Worker                                                     const SCEV *BECount) {
847*9880d681SAndroid Build Coastguard Worker   assert(SI->isSimple() && "Expected only non-volatile stores.");
848*9880d681SAndroid Build Coastguard Worker 
849*9880d681SAndroid Build Coastguard Worker   Value *StorePtr = SI->getPointerOperand();
850*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
851*9880d681SAndroid Build Coastguard Worker   APInt Stride = getStoreStride(StoreEv);
852*9880d681SAndroid Build Coastguard Worker   unsigned StoreSize = getStoreSizeInBytes(SI, DL);
853*9880d681SAndroid Build Coastguard Worker   bool NegStride = StoreSize == -Stride;
854*9880d681SAndroid Build Coastguard Worker 
855*9880d681SAndroid Build Coastguard Worker   // The store must be feeding a non-volatile load.
856*9880d681SAndroid Build Coastguard Worker   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
857*9880d681SAndroid Build Coastguard Worker   assert(LI->isSimple() && "Expected only non-volatile stores.");
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker   // See if the pointer expression is an AddRec like {base,+,1} on the current
860*9880d681SAndroid Build Coastguard Worker   // loop, which indicates a strided load.  If we have something else, it's a
861*9880d681SAndroid Build Coastguard Worker   // random load we can't handle.
862*9880d681SAndroid Build Coastguard Worker   const SCEVAddRecExpr *LoadEv =
863*9880d681SAndroid Build Coastguard Worker       cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
864*9880d681SAndroid Build Coastguard Worker 
865*9880d681SAndroid Build Coastguard Worker   // The trip count of the loop and the base pointer of the addrec SCEV is
866*9880d681SAndroid Build Coastguard Worker   // guaranteed to be loop invariant, which means that it should dominate the
867*9880d681SAndroid Build Coastguard Worker   // header.  This allows us to insert code for it in the preheader.
868*9880d681SAndroid Build Coastguard Worker   BasicBlock *Preheader = CurLoop->getLoopPreheader();
869*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(Preheader->getTerminator());
870*9880d681SAndroid Build Coastguard Worker   SCEVExpander Expander(*SE, *DL, "loop-idiom");
871*9880d681SAndroid Build Coastguard Worker 
872*9880d681SAndroid Build Coastguard Worker   const SCEV *StrStart = StoreEv->getStart();
873*9880d681SAndroid Build Coastguard Worker   unsigned StrAS = SI->getPointerAddressSpace();
874*9880d681SAndroid Build Coastguard Worker   Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
875*9880d681SAndroid Build Coastguard Worker 
876*9880d681SAndroid Build Coastguard Worker   // Handle negative strided loops.
877*9880d681SAndroid Build Coastguard Worker   if (NegStride)
878*9880d681SAndroid Build Coastguard Worker     StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
879*9880d681SAndroid Build Coastguard Worker 
880*9880d681SAndroid Build Coastguard Worker   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
881*9880d681SAndroid Build Coastguard Worker   // this into a memcpy in the loop preheader now if we want.  However, this
882*9880d681SAndroid Build Coastguard Worker   // would be unsafe to do if there is anything else in the loop that may read
883*9880d681SAndroid Build Coastguard Worker   // or write the memory region we're storing to.  This includes the load that
884*9880d681SAndroid Build Coastguard Worker   // feeds the stores.  Check for an alias by generating the base address and
885*9880d681SAndroid Build Coastguard Worker   // checking everything.
886*9880d681SAndroid Build Coastguard Worker   Value *StoreBasePtr = Expander.expandCodeFor(
887*9880d681SAndroid Build Coastguard Worker       StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
888*9880d681SAndroid Build Coastguard Worker 
889*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Instruction *, 1> Stores;
890*9880d681SAndroid Build Coastguard Worker   Stores.insert(SI);
891*9880d681SAndroid Build Coastguard Worker   if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
892*9880d681SAndroid Build Coastguard Worker                             StoreSize, *AA, Stores)) {
893*9880d681SAndroid Build Coastguard Worker     Expander.clear();
894*9880d681SAndroid Build Coastguard Worker     // If we generated new code for the base pointer, clean up.
895*9880d681SAndroid Build Coastguard Worker     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
896*9880d681SAndroid Build Coastguard Worker     return false;
897*9880d681SAndroid Build Coastguard Worker   }
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   const SCEV *LdStart = LoadEv->getStart();
900*9880d681SAndroid Build Coastguard Worker   unsigned LdAS = LI->getPointerAddressSpace();
901*9880d681SAndroid Build Coastguard Worker 
902*9880d681SAndroid Build Coastguard Worker   // Handle negative strided loops.
903*9880d681SAndroid Build Coastguard Worker   if (NegStride)
904*9880d681SAndroid Build Coastguard Worker     LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
905*9880d681SAndroid Build Coastguard Worker 
906*9880d681SAndroid Build Coastguard Worker   // For a memcpy, we have to make sure that the input array is not being
907*9880d681SAndroid Build Coastguard Worker   // mutated by the loop.
908*9880d681SAndroid Build Coastguard Worker   Value *LoadBasePtr = Expander.expandCodeFor(
909*9880d681SAndroid Build Coastguard Worker       LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
910*9880d681SAndroid Build Coastguard Worker 
911*9880d681SAndroid Build Coastguard Worker   if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
912*9880d681SAndroid Build Coastguard Worker                             *AA, Stores)) {
913*9880d681SAndroid Build Coastguard Worker     Expander.clear();
914*9880d681SAndroid Build Coastguard Worker     // If we generated new code for the base pointer, clean up.
915*9880d681SAndroid Build Coastguard Worker     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
916*9880d681SAndroid Build Coastguard Worker     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
917*9880d681SAndroid Build Coastguard Worker     return false;
918*9880d681SAndroid Build Coastguard Worker   }
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker   // Okay, everything is safe, we can transform this!
921*9880d681SAndroid Build Coastguard Worker 
922*9880d681SAndroid Build Coastguard Worker   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
923*9880d681SAndroid Build Coastguard Worker   // pointer size if it isn't already.
924*9880d681SAndroid Build Coastguard Worker   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
925*9880d681SAndroid Build Coastguard Worker 
926*9880d681SAndroid Build Coastguard Worker   const SCEV *NumBytesS =
927*9880d681SAndroid Build Coastguard Worker       SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
928*9880d681SAndroid Build Coastguard Worker   if (StoreSize != 1)
929*9880d681SAndroid Build Coastguard Worker     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
930*9880d681SAndroid Build Coastguard Worker                                SCEV::FlagNUW);
931*9880d681SAndroid Build Coastguard Worker 
932*9880d681SAndroid Build Coastguard Worker   Value *NumBytes =
933*9880d681SAndroid Build Coastguard Worker       Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
934*9880d681SAndroid Build Coastguard Worker 
935*9880d681SAndroid Build Coastguard Worker   CallInst *NewCall =
936*9880d681SAndroid Build Coastguard Worker       Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
937*9880d681SAndroid Build Coastguard Worker                            std::min(SI->getAlignment(), LI->getAlignment()));
938*9880d681SAndroid Build Coastguard Worker   NewCall->setDebugLoc(SI->getDebugLoc());
939*9880d681SAndroid Build Coastguard Worker 
940*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
941*9880d681SAndroid Build Coastguard Worker                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
942*9880d681SAndroid Build Coastguard Worker                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
943*9880d681SAndroid Build Coastguard Worker 
944*9880d681SAndroid Build Coastguard Worker   // Okay, the memcpy has been formed.  Zap the original store and anything that
945*9880d681SAndroid Build Coastguard Worker   // feeds into it.
946*9880d681SAndroid Build Coastguard Worker   deleteDeadInstruction(SI);
947*9880d681SAndroid Build Coastguard Worker   ++NumMemCpy;
948*9880d681SAndroid Build Coastguard Worker   return true;
949*9880d681SAndroid Build Coastguard Worker }
950*9880d681SAndroid Build Coastguard Worker 
runOnNoncountableLoop()951*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::runOnNoncountableLoop() {
952*9880d681SAndroid Build Coastguard Worker   return recognizePopcount();
953*9880d681SAndroid Build Coastguard Worker }
954*9880d681SAndroid Build Coastguard Worker 
955*9880d681SAndroid Build Coastguard Worker /// Check if the given conditional branch is based on the comparison between
956*9880d681SAndroid Build Coastguard Worker /// a variable and zero, and if the variable is non-zero, the control yields to
957*9880d681SAndroid Build Coastguard Worker /// the loop entry. If the branch matches the behavior, the variable involved
958*9880d681SAndroid Build Coastguard Worker /// in the comparion is returned. This function will be called to see if the
959*9880d681SAndroid Build Coastguard Worker /// precondition and postcondition of the loop are in desirable form.
matchCondition(BranchInst * BI,BasicBlock * LoopEntry)960*9880d681SAndroid Build Coastguard Worker static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
961*9880d681SAndroid Build Coastguard Worker   if (!BI || !BI->isConditional())
962*9880d681SAndroid Build Coastguard Worker     return nullptr;
963*9880d681SAndroid Build Coastguard Worker 
964*9880d681SAndroid Build Coastguard Worker   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
965*9880d681SAndroid Build Coastguard Worker   if (!Cond)
966*9880d681SAndroid Build Coastguard Worker     return nullptr;
967*9880d681SAndroid Build Coastguard Worker 
968*9880d681SAndroid Build Coastguard Worker   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
969*9880d681SAndroid Build Coastguard Worker   if (!CmpZero || !CmpZero->isZero())
970*9880d681SAndroid Build Coastguard Worker     return nullptr;
971*9880d681SAndroid Build Coastguard Worker 
972*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred = Cond->getPredicate();
973*9880d681SAndroid Build Coastguard Worker   if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
974*9880d681SAndroid Build Coastguard Worker       (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
975*9880d681SAndroid Build Coastguard Worker     return Cond->getOperand(0);
976*9880d681SAndroid Build Coastguard Worker 
977*9880d681SAndroid Build Coastguard Worker   return nullptr;
978*9880d681SAndroid Build Coastguard Worker }
979*9880d681SAndroid Build Coastguard Worker 
980*9880d681SAndroid Build Coastguard Worker /// Return true iff the idiom is detected in the loop.
981*9880d681SAndroid Build Coastguard Worker ///
982*9880d681SAndroid Build Coastguard Worker /// Additionally:
983*9880d681SAndroid Build Coastguard Worker /// 1) \p CntInst is set to the instruction counting the population bit.
984*9880d681SAndroid Build Coastguard Worker /// 2) \p CntPhi is set to the corresponding phi node.
985*9880d681SAndroid Build Coastguard Worker /// 3) \p Var is set to the value whose population bits are being counted.
986*9880d681SAndroid Build Coastguard Worker ///
987*9880d681SAndroid Build Coastguard Worker /// The core idiom we are trying to detect is:
988*9880d681SAndroid Build Coastguard Worker /// \code
989*9880d681SAndroid Build Coastguard Worker ///    if (x0 != 0)
990*9880d681SAndroid Build Coastguard Worker ///      goto loop-exit // the precondition of the loop
991*9880d681SAndroid Build Coastguard Worker ///    cnt0 = init-val;
992*9880d681SAndroid Build Coastguard Worker ///    do {
993*9880d681SAndroid Build Coastguard Worker ///       x1 = phi (x0, x2);
994*9880d681SAndroid Build Coastguard Worker ///       cnt1 = phi(cnt0, cnt2);
995*9880d681SAndroid Build Coastguard Worker ///
996*9880d681SAndroid Build Coastguard Worker ///       cnt2 = cnt1 + 1;
997*9880d681SAndroid Build Coastguard Worker ///        ...
998*9880d681SAndroid Build Coastguard Worker ///       x2 = x1 & (x1 - 1);
999*9880d681SAndroid Build Coastguard Worker ///        ...
1000*9880d681SAndroid Build Coastguard Worker ///    } while(x != 0);
1001*9880d681SAndroid Build Coastguard Worker ///
1002*9880d681SAndroid Build Coastguard Worker /// loop-exit:
1003*9880d681SAndroid Build Coastguard Worker /// \endcode
detectPopcountIdiom(Loop * CurLoop,BasicBlock * PreCondBB,Instruction * & CntInst,PHINode * & CntPhi,Value * & Var)1004*9880d681SAndroid Build Coastguard Worker static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1005*9880d681SAndroid Build Coastguard Worker                                 Instruction *&CntInst, PHINode *&CntPhi,
1006*9880d681SAndroid Build Coastguard Worker                                 Value *&Var) {
1007*9880d681SAndroid Build Coastguard Worker   // step 1: Check to see if the look-back branch match this pattern:
1008*9880d681SAndroid Build Coastguard Worker   //    "if (a!=0) goto loop-entry".
1009*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopEntry;
1010*9880d681SAndroid Build Coastguard Worker   Instruction *DefX2, *CountInst;
1011*9880d681SAndroid Build Coastguard Worker   Value *VarX1, *VarX0;
1012*9880d681SAndroid Build Coastguard Worker   PHINode *PhiX, *CountPhi;
1013*9880d681SAndroid Build Coastguard Worker 
1014*9880d681SAndroid Build Coastguard Worker   DefX2 = CountInst = nullptr;
1015*9880d681SAndroid Build Coastguard Worker   VarX1 = VarX0 = nullptr;
1016*9880d681SAndroid Build Coastguard Worker   PhiX = CountPhi = nullptr;
1017*9880d681SAndroid Build Coastguard Worker   LoopEntry = *(CurLoop->block_begin());
1018*9880d681SAndroid Build Coastguard Worker 
1019*9880d681SAndroid Build Coastguard Worker   // step 1: Check if the loop-back branch is in desirable form.
1020*9880d681SAndroid Build Coastguard Worker   {
1021*9880d681SAndroid Build Coastguard Worker     if (Value *T = matchCondition(
1022*9880d681SAndroid Build Coastguard Worker             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1023*9880d681SAndroid Build Coastguard Worker       DefX2 = dyn_cast<Instruction>(T);
1024*9880d681SAndroid Build Coastguard Worker     else
1025*9880d681SAndroid Build Coastguard Worker       return false;
1026*9880d681SAndroid Build Coastguard Worker   }
1027*9880d681SAndroid Build Coastguard Worker 
1028*9880d681SAndroid Build Coastguard Worker   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1029*9880d681SAndroid Build Coastguard Worker   {
1030*9880d681SAndroid Build Coastguard Worker     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1031*9880d681SAndroid Build Coastguard Worker       return false;
1032*9880d681SAndroid Build Coastguard Worker 
1033*9880d681SAndroid Build Coastguard Worker     BinaryOperator *SubOneOp;
1034*9880d681SAndroid Build Coastguard Worker 
1035*9880d681SAndroid Build Coastguard Worker     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1036*9880d681SAndroid Build Coastguard Worker       VarX1 = DefX2->getOperand(1);
1037*9880d681SAndroid Build Coastguard Worker     else {
1038*9880d681SAndroid Build Coastguard Worker       VarX1 = DefX2->getOperand(0);
1039*9880d681SAndroid Build Coastguard Worker       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1040*9880d681SAndroid Build Coastguard Worker     }
1041*9880d681SAndroid Build Coastguard Worker     if (!SubOneOp)
1042*9880d681SAndroid Build Coastguard Worker       return false;
1043*9880d681SAndroid Build Coastguard Worker 
1044*9880d681SAndroid Build Coastguard Worker     Instruction *SubInst = cast<Instruction>(SubOneOp);
1045*9880d681SAndroid Build Coastguard Worker     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1046*9880d681SAndroid Build Coastguard Worker     if (!Dec ||
1047*9880d681SAndroid Build Coastguard Worker         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1048*9880d681SAndroid Build Coastguard Worker           (SubInst->getOpcode() == Instruction::Add &&
1049*9880d681SAndroid Build Coastguard Worker            Dec->isAllOnesValue()))) {
1050*9880d681SAndroid Build Coastguard Worker       return false;
1051*9880d681SAndroid Build Coastguard Worker     }
1052*9880d681SAndroid Build Coastguard Worker   }
1053*9880d681SAndroid Build Coastguard Worker 
1054*9880d681SAndroid Build Coastguard Worker   // step 3: Check the recurrence of variable X
1055*9880d681SAndroid Build Coastguard Worker   {
1056*9880d681SAndroid Build Coastguard Worker     PhiX = dyn_cast<PHINode>(VarX1);
1057*9880d681SAndroid Build Coastguard Worker     if (!PhiX ||
1058*9880d681SAndroid Build Coastguard Worker         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
1059*9880d681SAndroid Build Coastguard Worker       return false;
1060*9880d681SAndroid Build Coastguard Worker     }
1061*9880d681SAndroid Build Coastguard Worker   }
1062*9880d681SAndroid Build Coastguard Worker 
1063*9880d681SAndroid Build Coastguard Worker   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1064*9880d681SAndroid Build Coastguard Worker   {
1065*9880d681SAndroid Build Coastguard Worker     CountInst = nullptr;
1066*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1067*9880d681SAndroid Build Coastguard Worker                               IterE = LoopEntry->end();
1068*9880d681SAndroid Build Coastguard Worker          Iter != IterE; Iter++) {
1069*9880d681SAndroid Build Coastguard Worker       Instruction *Inst = &*Iter;
1070*9880d681SAndroid Build Coastguard Worker       if (Inst->getOpcode() != Instruction::Add)
1071*9880d681SAndroid Build Coastguard Worker         continue;
1072*9880d681SAndroid Build Coastguard Worker 
1073*9880d681SAndroid Build Coastguard Worker       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1074*9880d681SAndroid Build Coastguard Worker       if (!Inc || !Inc->isOne())
1075*9880d681SAndroid Build Coastguard Worker         continue;
1076*9880d681SAndroid Build Coastguard Worker 
1077*9880d681SAndroid Build Coastguard Worker       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
1078*9880d681SAndroid Build Coastguard Worker       if (!Phi || Phi->getParent() != LoopEntry)
1079*9880d681SAndroid Build Coastguard Worker         continue;
1080*9880d681SAndroid Build Coastguard Worker 
1081*9880d681SAndroid Build Coastguard Worker       // Check if the result of the instruction is live of the loop.
1082*9880d681SAndroid Build Coastguard Worker       bool LiveOutLoop = false;
1083*9880d681SAndroid Build Coastguard Worker       for (User *U : Inst->users()) {
1084*9880d681SAndroid Build Coastguard Worker         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1085*9880d681SAndroid Build Coastguard Worker           LiveOutLoop = true;
1086*9880d681SAndroid Build Coastguard Worker           break;
1087*9880d681SAndroid Build Coastguard Worker         }
1088*9880d681SAndroid Build Coastguard Worker       }
1089*9880d681SAndroid Build Coastguard Worker 
1090*9880d681SAndroid Build Coastguard Worker       if (LiveOutLoop) {
1091*9880d681SAndroid Build Coastguard Worker         CountInst = Inst;
1092*9880d681SAndroid Build Coastguard Worker         CountPhi = Phi;
1093*9880d681SAndroid Build Coastguard Worker         break;
1094*9880d681SAndroid Build Coastguard Worker       }
1095*9880d681SAndroid Build Coastguard Worker     }
1096*9880d681SAndroid Build Coastguard Worker 
1097*9880d681SAndroid Build Coastguard Worker     if (!CountInst)
1098*9880d681SAndroid Build Coastguard Worker       return false;
1099*9880d681SAndroid Build Coastguard Worker   }
1100*9880d681SAndroid Build Coastguard Worker 
1101*9880d681SAndroid Build Coastguard Worker   // step 5: check if the precondition is in this form:
1102*9880d681SAndroid Build Coastguard Worker   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1103*9880d681SAndroid Build Coastguard Worker   {
1104*9880d681SAndroid Build Coastguard Worker     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1105*9880d681SAndroid Build Coastguard Worker     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1106*9880d681SAndroid Build Coastguard Worker     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1107*9880d681SAndroid Build Coastguard Worker       return false;
1108*9880d681SAndroid Build Coastguard Worker 
1109*9880d681SAndroid Build Coastguard Worker     CntInst = CountInst;
1110*9880d681SAndroid Build Coastguard Worker     CntPhi = CountPhi;
1111*9880d681SAndroid Build Coastguard Worker     Var = T;
1112*9880d681SAndroid Build Coastguard Worker   }
1113*9880d681SAndroid Build Coastguard Worker 
1114*9880d681SAndroid Build Coastguard Worker   return true;
1115*9880d681SAndroid Build Coastguard Worker }
1116*9880d681SAndroid Build Coastguard Worker 
1117*9880d681SAndroid Build Coastguard Worker /// Recognizes a population count idiom in a non-countable loop.
1118*9880d681SAndroid Build Coastguard Worker ///
1119*9880d681SAndroid Build Coastguard Worker /// If detected, transforms the relevant code to issue the popcount intrinsic
1120*9880d681SAndroid Build Coastguard Worker /// function call, and returns true; otherwise, returns false.
recognizePopcount()1121*9880d681SAndroid Build Coastguard Worker bool LoopIdiomRecognize::recognizePopcount() {
1122*9880d681SAndroid Build Coastguard Worker   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1123*9880d681SAndroid Build Coastguard Worker     return false;
1124*9880d681SAndroid Build Coastguard Worker 
1125*9880d681SAndroid Build Coastguard Worker   // Counting population are usually conducted by few arithmetic instructions.
1126*9880d681SAndroid Build Coastguard Worker   // Such instructions can be easily "absorbed" by vacant slots in a
1127*9880d681SAndroid Build Coastguard Worker   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1128*9880d681SAndroid Build Coastguard Worker   // in a compact loop.
1129*9880d681SAndroid Build Coastguard Worker 
1130*9880d681SAndroid Build Coastguard Worker   // Give up if the loop has multiple blocks or multiple backedges.
1131*9880d681SAndroid Build Coastguard Worker   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1132*9880d681SAndroid Build Coastguard Worker     return false;
1133*9880d681SAndroid Build Coastguard Worker 
1134*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopBody = *(CurLoop->block_begin());
1135*9880d681SAndroid Build Coastguard Worker   if (LoopBody->size() >= 20) {
1136*9880d681SAndroid Build Coastguard Worker     // The loop is too big, bail out.
1137*9880d681SAndroid Build Coastguard Worker     return false;
1138*9880d681SAndroid Build Coastguard Worker   }
1139*9880d681SAndroid Build Coastguard Worker 
1140*9880d681SAndroid Build Coastguard Worker   // It should have a preheader containing nothing but an unconditional branch.
1141*9880d681SAndroid Build Coastguard Worker   BasicBlock *PH = CurLoop->getLoopPreheader();
1142*9880d681SAndroid Build Coastguard Worker   if (!PH)
1143*9880d681SAndroid Build Coastguard Worker     return false;
1144*9880d681SAndroid Build Coastguard Worker   if (&PH->front() != PH->getTerminator())
1145*9880d681SAndroid Build Coastguard Worker     return false;
1146*9880d681SAndroid Build Coastguard Worker   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1147*9880d681SAndroid Build Coastguard Worker   if (!EntryBI || EntryBI->isConditional())
1148*9880d681SAndroid Build Coastguard Worker     return false;
1149*9880d681SAndroid Build Coastguard Worker 
1150*9880d681SAndroid Build Coastguard Worker   // It should have a precondition block where the generated popcount instrinsic
1151*9880d681SAndroid Build Coastguard Worker   // function can be inserted.
1152*9880d681SAndroid Build Coastguard Worker   auto *PreCondBB = PH->getSinglePredecessor();
1153*9880d681SAndroid Build Coastguard Worker   if (!PreCondBB)
1154*9880d681SAndroid Build Coastguard Worker     return false;
1155*9880d681SAndroid Build Coastguard Worker   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1156*9880d681SAndroid Build Coastguard Worker   if (!PreCondBI || PreCondBI->isUnconditional())
1157*9880d681SAndroid Build Coastguard Worker     return false;
1158*9880d681SAndroid Build Coastguard Worker 
1159*9880d681SAndroid Build Coastguard Worker   Instruction *CntInst;
1160*9880d681SAndroid Build Coastguard Worker   PHINode *CntPhi;
1161*9880d681SAndroid Build Coastguard Worker   Value *Val;
1162*9880d681SAndroid Build Coastguard Worker   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1163*9880d681SAndroid Build Coastguard Worker     return false;
1164*9880d681SAndroid Build Coastguard Worker 
1165*9880d681SAndroid Build Coastguard Worker   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1166*9880d681SAndroid Build Coastguard Worker   return true;
1167*9880d681SAndroid Build Coastguard Worker }
1168*9880d681SAndroid Build Coastguard Worker 
createPopcntIntrinsic(IRBuilder<> & IRBuilder,Value * Val,const DebugLoc & DL)1169*9880d681SAndroid Build Coastguard Worker static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1170*9880d681SAndroid Build Coastguard Worker                                        const DebugLoc &DL) {
1171*9880d681SAndroid Build Coastguard Worker   Value *Ops[] = {Val};
1172*9880d681SAndroid Build Coastguard Worker   Type *Tys[] = {Val->getType()};
1173*9880d681SAndroid Build Coastguard Worker 
1174*9880d681SAndroid Build Coastguard Worker   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1175*9880d681SAndroid Build Coastguard Worker   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1176*9880d681SAndroid Build Coastguard Worker   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1177*9880d681SAndroid Build Coastguard Worker   CI->setDebugLoc(DL);
1178*9880d681SAndroid Build Coastguard Worker 
1179*9880d681SAndroid Build Coastguard Worker   return CI;
1180*9880d681SAndroid Build Coastguard Worker }
1181*9880d681SAndroid Build Coastguard Worker 
transformLoopToPopcount(BasicBlock * PreCondBB,Instruction * CntInst,PHINode * CntPhi,Value * Var)1182*9880d681SAndroid Build Coastguard Worker void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1183*9880d681SAndroid Build Coastguard Worker                                                  Instruction *CntInst,
1184*9880d681SAndroid Build Coastguard Worker                                                  PHINode *CntPhi, Value *Var) {
1185*9880d681SAndroid Build Coastguard Worker   BasicBlock *PreHead = CurLoop->getLoopPreheader();
1186*9880d681SAndroid Build Coastguard Worker   auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1187*9880d681SAndroid Build Coastguard Worker   const DebugLoc DL = CntInst->getDebugLoc();
1188*9880d681SAndroid Build Coastguard Worker 
1189*9880d681SAndroid Build Coastguard Worker   // Assuming before transformation, the loop is following:
1190*9880d681SAndroid Build Coastguard Worker   //  if (x) // the precondition
1191*9880d681SAndroid Build Coastguard Worker   //     do { cnt++; x &= x - 1; } while(x);
1192*9880d681SAndroid Build Coastguard Worker 
1193*9880d681SAndroid Build Coastguard Worker   // Step 1: Insert the ctpop instruction at the end of the precondition block
1194*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(PreCondBr);
1195*9880d681SAndroid Build Coastguard Worker   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1196*9880d681SAndroid Build Coastguard Worker   {
1197*9880d681SAndroid Build Coastguard Worker     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1198*9880d681SAndroid Build Coastguard Worker     NewCount = PopCntZext =
1199*9880d681SAndroid Build Coastguard Worker         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1200*9880d681SAndroid Build Coastguard Worker 
1201*9880d681SAndroid Build Coastguard Worker     if (NewCount != PopCnt)
1202*9880d681SAndroid Build Coastguard Worker       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1203*9880d681SAndroid Build Coastguard Worker 
1204*9880d681SAndroid Build Coastguard Worker     // TripCnt is exactly the number of iterations the loop has
1205*9880d681SAndroid Build Coastguard Worker     TripCnt = NewCount;
1206*9880d681SAndroid Build Coastguard Worker 
1207*9880d681SAndroid Build Coastguard Worker     // If the population counter's initial value is not zero, insert Add Inst.
1208*9880d681SAndroid Build Coastguard Worker     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1209*9880d681SAndroid Build Coastguard Worker     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1210*9880d681SAndroid Build Coastguard Worker     if (!InitConst || !InitConst->isZero()) {
1211*9880d681SAndroid Build Coastguard Worker       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1212*9880d681SAndroid Build Coastguard Worker       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1213*9880d681SAndroid Build Coastguard Worker     }
1214*9880d681SAndroid Build Coastguard Worker   }
1215*9880d681SAndroid Build Coastguard Worker 
1216*9880d681SAndroid Build Coastguard Worker   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1217*9880d681SAndroid Build Coastguard Worker   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1218*9880d681SAndroid Build Coastguard Worker   //   function would be partial dead code, and downstream passes will drag
1219*9880d681SAndroid Build Coastguard Worker   //   it back from the precondition block to the preheader.
1220*9880d681SAndroid Build Coastguard Worker   {
1221*9880d681SAndroid Build Coastguard Worker     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1222*9880d681SAndroid Build Coastguard Worker 
1223*9880d681SAndroid Build Coastguard Worker     Value *Opnd0 = PopCntZext;
1224*9880d681SAndroid Build Coastguard Worker     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1225*9880d681SAndroid Build Coastguard Worker     if (PreCond->getOperand(0) != Var)
1226*9880d681SAndroid Build Coastguard Worker       std::swap(Opnd0, Opnd1);
1227*9880d681SAndroid Build Coastguard Worker 
1228*9880d681SAndroid Build Coastguard Worker     ICmpInst *NewPreCond = cast<ICmpInst>(
1229*9880d681SAndroid Build Coastguard Worker         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1230*9880d681SAndroid Build Coastguard Worker     PreCondBr->setCondition(NewPreCond);
1231*9880d681SAndroid Build Coastguard Worker 
1232*9880d681SAndroid Build Coastguard Worker     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1233*9880d681SAndroid Build Coastguard Worker   }
1234*9880d681SAndroid Build Coastguard Worker 
1235*9880d681SAndroid Build Coastguard Worker   // Step 3: Note that the population count is exactly the trip count of the
1236*9880d681SAndroid Build Coastguard Worker   // loop in question, which enable us to to convert the loop from noncountable
1237*9880d681SAndroid Build Coastguard Worker   // loop into a countable one. The benefit is twofold:
1238*9880d681SAndroid Build Coastguard Worker   //
1239*9880d681SAndroid Build Coastguard Worker   //  - If the loop only counts population, the entire loop becomes dead after
1240*9880d681SAndroid Build Coastguard Worker   //    the transformation. It is a lot easier to prove a countable loop dead
1241*9880d681SAndroid Build Coastguard Worker   //    than to prove a noncountable one. (In some C dialects, an infinite loop
1242*9880d681SAndroid Build Coastguard Worker   //    isn't dead even if it computes nothing useful. In general, DCE needs
1243*9880d681SAndroid Build Coastguard Worker   //    to prove a noncountable loop finite before safely delete it.)
1244*9880d681SAndroid Build Coastguard Worker   //
1245*9880d681SAndroid Build Coastguard Worker   //  - If the loop also performs something else, it remains alive.
1246*9880d681SAndroid Build Coastguard Worker   //    Since it is transformed to countable form, it can be aggressively
1247*9880d681SAndroid Build Coastguard Worker   //    optimized by some optimizations which are in general not applicable
1248*9880d681SAndroid Build Coastguard Worker   //    to a noncountable loop.
1249*9880d681SAndroid Build Coastguard Worker   //
1250*9880d681SAndroid Build Coastguard Worker   // After this step, this loop (conceptually) would look like following:
1251*9880d681SAndroid Build Coastguard Worker   //   newcnt = __builtin_ctpop(x);
1252*9880d681SAndroid Build Coastguard Worker   //   t = newcnt;
1253*9880d681SAndroid Build Coastguard Worker   //   if (x)
1254*9880d681SAndroid Build Coastguard Worker   //     do { cnt++; x &= x-1; t--) } while (t > 0);
1255*9880d681SAndroid Build Coastguard Worker   BasicBlock *Body = *(CurLoop->block_begin());
1256*9880d681SAndroid Build Coastguard Worker   {
1257*9880d681SAndroid Build Coastguard Worker     auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1258*9880d681SAndroid Build Coastguard Worker     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1259*9880d681SAndroid Build Coastguard Worker     Type *Ty = TripCnt->getType();
1260*9880d681SAndroid Build Coastguard Worker 
1261*9880d681SAndroid Build Coastguard Worker     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1262*9880d681SAndroid Build Coastguard Worker 
1263*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(LbCond);
1264*9880d681SAndroid Build Coastguard Worker     Instruction *TcDec = cast<Instruction>(
1265*9880d681SAndroid Build Coastguard Worker         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1266*9880d681SAndroid Build Coastguard Worker                           "tcdec", false, true));
1267*9880d681SAndroid Build Coastguard Worker 
1268*9880d681SAndroid Build Coastguard Worker     TcPhi->addIncoming(TripCnt, PreHead);
1269*9880d681SAndroid Build Coastguard Worker     TcPhi->addIncoming(TcDec, Body);
1270*9880d681SAndroid Build Coastguard Worker 
1271*9880d681SAndroid Build Coastguard Worker     CmpInst::Predicate Pred =
1272*9880d681SAndroid Build Coastguard Worker         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1273*9880d681SAndroid Build Coastguard Worker     LbCond->setPredicate(Pred);
1274*9880d681SAndroid Build Coastguard Worker     LbCond->setOperand(0, TcDec);
1275*9880d681SAndroid Build Coastguard Worker     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1276*9880d681SAndroid Build Coastguard Worker   }
1277*9880d681SAndroid Build Coastguard Worker 
1278*9880d681SAndroid Build Coastguard Worker   // Step 4: All the references to the original population counter outside
1279*9880d681SAndroid Build Coastguard Worker   //  the loop are replaced with the NewCount -- the value returned from
1280*9880d681SAndroid Build Coastguard Worker   //  __builtin_ctpop().
1281*9880d681SAndroid Build Coastguard Worker   CntInst->replaceUsesOutsideBlock(NewCount, Body);
1282*9880d681SAndroid Build Coastguard Worker 
1283*9880d681SAndroid Build Coastguard Worker   // step 5: Forget the "non-computable" trip-count SCEV associated with the
1284*9880d681SAndroid Build Coastguard Worker   //   loop. The loop would otherwise not be deleted even if it becomes empty.
1285*9880d681SAndroid Build Coastguard Worker   SE->forgetLoop(CurLoop);
1286*9880d681SAndroid Build Coastguard Worker }
1287