blob: 445434c9f16f72df2e2c6b590af4747b04beb427 [file] [log] [blame]
Chris Lattner81ae3f22010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements an idiom recognizer that transforms simple loops into a
11// non-loop form. In cases that this kicks in, it can be a significant
12// performance win.
13//
14//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000019// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000020// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
25// Beware that isel's default lowering for ctpop is highly inefficient for
26// i64 and larger types when i64 is legal and the value has few bits set. It
27// would be good to enhance isel to emit a loop for ctpop in this case.
28//
29// We should enhance the memset/memcpy recognition to handle multiple stores in
30// the loop. This would handle things like:
31// void foo(_Complex float *P)
32// for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
Chris Lattner8fac5db2011-01-02 23:19:45 +000033//
Chris Lattnerbc661d62011-02-21 02:08:54 +000034// We should enhance this to handle negative strides through memory.
35// Alternatively (and perhaps better) we could rely on an earlier pass to force
36// forward iteration through memory, which is generally better for cache
37// behavior. Negative strides *do* happen for memset/memcpy loops.
38//
Chris Lattner02a97762011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattner0469e012011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000043
44#define DEBUG_TYPE "loop-idiom"
45#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000047#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner29e14ed2010-12-26 23:42:51 +000049#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000051#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000052#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000058#include "llvm/Support/Debug.h"
59#include "llvm/Support/raw_ostream.h"
Chris Lattnere6b261f2011-02-18 22:22:15 +000060#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000061#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000062using namespace llvm;
63
Chandler Carruth099f5cb02012-11-02 08:33:25 +000064STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
65STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000066
67namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000068
69 class LoopIdiomRecognize;
70
71 /// This class defines some utility functions for loop idiom recognization.
72 class LIRUtil {
73 public:
74 /// Return true iff the block contains nothing but an uncondition branch
75 /// (aka goto instruction).
76 static bool isAlmostEmpty(BasicBlock *);
77
78 static BranchInst *getBranch(BasicBlock *BB) {
79 return dyn_cast<BranchInst>(BB->getTerminator());
80 }
81
82 /// Return the condition of the branch terminating the given basic block.
83 static Value *getBrCondtion(BasicBlock *);
84
Matt Arsenaultfb183232013-07-22 18:59:58 +000085 /// Derive the precondition block (i.e the block that guards the loop
Shuxin Yang95de7c32012-12-09 03:12:46 +000086 /// preheader) from the given preheader.
87 static BasicBlock *getPrecondBb(BasicBlock *PreHead);
88 };
89
90 /// This class is to recoginize idioms of population-count conducted in
91 /// a noncountable loop. Currently it only recognizes this pattern:
92 /// \code
93 /// while(x) {cnt++; ...; x &= x - 1; ...}
94 /// \endcode
95 class NclPopcountRecognize {
96 LoopIdiomRecognize &LIR;
97 Loop *CurLoop;
98 BasicBlock *PreCondBB;
99
100 typedef IRBuilder<> IRBuilderTy;
101
102 public:
103 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
104 bool recognize();
105
106 private:
107 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
108 /// the idiom.
109 bool preliminaryScreen();
110
111 /// Check if the given conditional branch is based on the comparison
Alp Tokercb402912014-01-24 17:20:08 +0000112 /// between a variable and zero, and if the variable is non-zero, the
113 /// control yields to the loop entry. If the branch matches the behavior,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000114 /// the variable involved in the comparion is returned. This function will
Matt Arsenaultfb183232013-07-22 18:59:58 +0000115 /// be called to see if the precondition and postcondition of the loop
Shuxin Yang95de7c32012-12-09 03:12:46 +0000116 /// are in desirable form.
117 Value *matchCondition (BranchInst *Br, BasicBlock *NonZeroTarget) const;
118
119 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
120 /// is set to the instruction counting the pupulation bit. 2) \p CntPhi
121 /// is set to the corresponding phi node. 3) \p Var is set to the value
122 /// whose population bits are being counted.
123 bool detectIdiom
124 (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
125
126 /// Insert ctpop intrinsic function and some obviously dead instructions.
127 void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var);
128
129 /// Create llvm.ctpop.* intrinsic function.
130 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
131 };
132
Chris Lattner81ae3f22010-12-26 19:39:38 +0000133 class LoopIdiomRecognize : public LoopPass {
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000134 Loop *CurLoop;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000135 const DataLayout *DL;
Chris Lattner8455b6e2011-01-02 19:01:03 +0000136 DominatorTree *DT;
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000137 ScalarEvolution *SE;
Chris Lattnere6b261f2011-02-18 22:22:15 +0000138 TargetLibraryInfo *TLI;
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000139 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000140 public:
141 static char ID;
142 explicit LoopIdiomRecognize() : LoopPass(ID) {
143 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000144 DL = 0; DT = 0; SE = 0; TLI = 0; TTI = 0;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000145 }
146
147 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner8455b6e2011-01-02 19:01:03 +0000148 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
149 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattner81ae3f22010-12-26 19:39:38 +0000150
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000151 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000152 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trick328b2232011-03-14 16:48:10 +0000153
Chris Lattner0f4a6402011-02-19 19:31:39 +0000154 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
155 unsigned StoreAlignment,
156 Value *SplatValue, Instruction *TheStore,
157 const SCEVAddRecExpr *Ev,
158 const SCEV *BECount);
Chris Lattner85b6d812011-01-02 03:37:56 +0000159 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
160 const SCEVAddRecExpr *StoreEv,
161 const SCEVAddRecExpr *LoadEv,
162 const SCEV *BECount);
Andrew Trick328b2232011-03-14 16:48:10 +0000163
Chris Lattner81ae3f22010-12-26 19:39:38 +0000164 /// This transformation requires natural loop information & requires that
165 /// loop preheaders be inserted into the CFG.
166 ///
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<LoopInfo>();
169 AU.addPreserved<LoopInfo>();
170 AU.addRequiredID(LoopSimplifyID);
171 AU.addPreservedID(LoopSimplifyID);
172 AU.addRequiredID(LCSSAID);
173 AU.addPreservedID(LCSSAID);
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000174 AU.addRequired<AliasAnalysis>();
175 AU.addPreserved<AliasAnalysis>();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000176 AU.addRequired<ScalarEvolution>();
177 AU.addPreserved<ScalarEvolution>();
Chandler Carruth73523022014-01-13 13:07:17 +0000178 AU.addPreserved<DominatorTreeWrapperPass>();
179 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnere6b261f2011-02-18 22:22:15 +0000180 AU.addRequired<TargetLibraryInfo>();
Chandler Carruth342cc252013-01-07 09:17:41 +0000181 AU.addRequired<TargetTransformInfo>();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000182 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000183
184 const DataLayout *getDataLayout() {
Rafael Espindola93512512014-02-25 17:30:31 +0000185 if (DL)
186 return DL;
187 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
188 DL = DLP ? &DLP->getDataLayout() : 0;
189 return DL;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000190 }
191
192 DominatorTree *getDominatorTree() {
Chandler Carruth73523022014-01-13 13:07:17 +0000193 return DT ? DT
194 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000195 }
196
197 ScalarEvolution *getScalarEvolution() {
198 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
199 }
200
201 TargetLibraryInfo *getTargetLibraryInfo() {
202 return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
203 }
204
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000205 const TargetTransformInfo *getTargetTransformInfo() {
Chandler Carruth342cc252013-01-07 09:17:41 +0000206 return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000207 }
208
209 Loop *getLoop() const { return CurLoop; }
210
211 private:
212 bool runOnNoncountableLoop();
213 bool runOnCountableLoop();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000214 };
215}
216
217char LoopIdiomRecognize::ID = 0;
218INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
219 false, false)
220INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chandler Carruth73523022014-01-13 13:07:17 +0000221INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000222INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
223INITIALIZE_PASS_DEPENDENCY(LCSSA)
224INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000225INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000226INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth342cc252013-01-07 09:17:41 +0000227INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000228INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
229 false, false)
230
231Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
232
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000233/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000234/// and zero out all the operands of this instruction. If any of them become
235/// dead, delete them and the computation tree that feeds them.
236///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000237static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
238 const TargetLibraryInfo *TLI) {
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000239 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trick328b2232011-03-14 16:48:10 +0000240
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000241 NowDeadInsts.push_back(I);
Andrew Trick328b2232011-03-14 16:48:10 +0000242
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000243 // Before we touch this instruction, remove it from SE!
244 do {
245 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trick328b2232011-03-14 16:48:10 +0000246
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000247 // This instruction is dead, zap it, in stages. Start by removing it from
248 // SCEV.
249 SE.forgetValue(DeadInst);
Andrew Trick328b2232011-03-14 16:48:10 +0000250
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000251 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
252 Value *Op = DeadInst->getOperand(op);
253 DeadInst->setOperand(op, 0);
Andrew Trick328b2232011-03-14 16:48:10 +0000254
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000255 // If this operand just became dead, add it to the NowDeadInsts list.
256 if (!Op->use_empty()) continue;
Andrew Trick328b2232011-03-14 16:48:10 +0000257
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000258 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000259 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000260 NowDeadInsts.push_back(OpI);
261 }
Andrew Trick328b2232011-03-14 16:48:10 +0000262
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000263 DeadInst->eraseFromParent();
Andrew Trick328b2232011-03-14 16:48:10 +0000264
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000265 } while (!NowDeadInsts.empty());
266}
267
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000268/// deleteIfDeadInstruction - If the specified value is a dead instruction,
269/// delete it and any recursively used instructions.
270static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
271 const TargetLibraryInfo *TLI) {
272 if (Instruction *I = dyn_cast<Instruction>(V))
273 if (isInstructionTriviallyDead(I, TLI))
274 deleteDeadInstruction(I, SE, TLI);
275}
276
Shuxin Yang95de7c32012-12-09 03:12:46 +0000277//===----------------------------------------------------------------------===//
278//
279// Implementation of LIRUtil
280//
281//===----------------------------------------------------------------------===//
282
Matt Arsenaultfb183232013-07-22 18:59:58 +0000283// This function will return true iff the given block contains nothing but goto.
284// A typical usage of this function is to check if the preheader function is
285// "almost" empty such that generated intrinsic functions can be moved across
286// the preheader and be placed at the end of the precondition block without
287// the concern of breaking data dependence.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000288bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
289 if (BranchInst *Br = getBranch(BB)) {
290 return Br->isUnconditional() && BB->size() == 1;
291 }
292 return false;
293}
294
295Value *LIRUtil::getBrCondtion(BasicBlock *BB) {
296 BranchInst *Br = getBranch(BB);
297 return Br ? Br->getCondition() : 0;
298}
299
300BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
301 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
302 BranchInst *Br = getBranch(BB);
303 return Br && Br->isConditional() ? BB : 0;
304 }
305 return 0;
306}
307
308//===----------------------------------------------------------------------===//
309//
310// Implementation of NclPopcountRecognize
311//
312//===----------------------------------------------------------------------===//
313
314NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
315 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(0) {
316}
317
318bool NclPopcountRecognize::preliminaryScreen() {
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000319 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
Chandler Carruth50a36cd2013-01-07 03:16:03 +0000320 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000321 return false;
322
Robert Wilhelm2788d3e2013-09-28 13:42:22 +0000323 // Counting population are usually conducted by few arithmetic instructions.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000324 // Such instructions can be easilly "absorbed" by vacant slots in a
325 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
326 // in a compact loop.
327
328 // Give up if the loop has multiple blocks or multiple backedges.
329 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
330 return false;
331
332 BasicBlock *LoopBody = *(CurLoop->block_begin());
333 if (LoopBody->size() >= 20) {
334 // The loop is too big, bail out.
335 return false;
336 }
337
338 // It should have a preheader containing nothing but a goto instruction.
339 BasicBlock *PreHead = CurLoop->getLoopPreheader();
340 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
341 return false;
342
343 // It should have a precondition block where the generated popcount instrinsic
344 // function will be inserted.
345 PreCondBB = LIRUtil::getPrecondBb(PreHead);
346 if (!PreCondBB)
347 return false;
Matt Arsenaultfb183232013-07-22 18:59:58 +0000348
Shuxin Yang95de7c32012-12-09 03:12:46 +0000349 return true;
350}
351
352Value *NclPopcountRecognize::matchCondition (BranchInst *Br,
353 BasicBlock *LoopEntry) const {
354 if (!Br || !Br->isConditional())
355 return 0;
356
357 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
358 if (!Cond)
359 return 0;
360
361 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
362 if (!CmpZero || !CmpZero->isZero())
363 return 0;
364
365 ICmpInst::Predicate Pred = Cond->getPredicate();
366 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
367 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
368 return Cond->getOperand(0);
369
370 return 0;
371}
372
373bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
374 PHINode *&CntPhi,
375 Value *&Var) const {
376 // Following code tries to detect this idiom:
377 //
378 // if (x0 != 0)
379 // goto loop-exit // the precondition of the loop
380 // cnt0 = init-val;
381 // do {
382 // x1 = phi (x0, x2);
383 // cnt1 = phi(cnt0, cnt2);
384 //
385 // cnt2 = cnt1 + 1;
386 // ...
387 // x2 = x1 & (x1 - 1);
388 // ...
389 // } while(x != 0);
390 //
391 // loop-exit:
392 //
393
394 // step 1: Check to see if the look-back branch match this pattern:
395 // "if (a!=0) goto loop-entry".
396 BasicBlock *LoopEntry;
397 Instruction *DefX2, *CountInst;
398 Value *VarX1, *VarX0;
399 PHINode *PhiX, *CountPhi;
400
401 DefX2 = CountInst = 0;
402 VarX1 = VarX0 = 0;
403 PhiX = CountPhi = 0;
404 LoopEntry = *(CurLoop->block_begin());
405
406 // step 1: Check if the loop-back branch is in desirable form.
407 {
408 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
409 DefX2 = dyn_cast<Instruction>(T);
410 else
411 return false;
412 }
413
414 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
415 {
Shuxin Yangc5c730b2013-01-10 23:32:01 +0000416 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000417 return false;
418
419 BinaryOperator *SubOneOp;
420
421 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
422 VarX1 = DefX2->getOperand(1);
423 else {
424 VarX1 = DefX2->getOperand(0);
425 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
426 }
427 if (!SubOneOp)
428 return false;
429
430 Instruction *SubInst = cast<Instruction>(SubOneOp);
431 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
432 if (!Dec ||
433 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
434 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
435 return false;
436 }
437 }
438
439 // step 3: Check the recurrence of variable X
440 {
441 PhiX = dyn_cast<PHINode>(VarX1);
442 if (!PhiX ||
443 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
444 return false;
445 }
446 }
447
448 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
449 {
450 CountInst = NULL;
451 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
452 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
453 Instruction *Inst = Iter;
454 if (Inst->getOpcode() != Instruction::Add)
455 continue;
456
457 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
458 if (!Inc || !Inc->isOne())
459 continue;
460
461 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
462 if (!Phi || Phi->getParent() != LoopEntry)
463 continue;
464
465 // Check if the result of the instruction is live of the loop.
466 bool LiveOutLoop = false;
467 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
468 I != E; I++) {
469 if ((cast<Instruction>(*I))->getParent() != LoopEntry) {
470 LiveOutLoop = true; break;
471 }
472 }
473
474 if (LiveOutLoop) {
475 CountInst = Inst;
476 CountPhi = Phi;
477 break;
478 }
479 }
480
481 if (!CountInst)
482 return false;
483 }
484
485 // step 5: check if the precondition is in this form:
486 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
487 {
488 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
489 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
490 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
491 return false;
492
493 CntInst = CountInst;
494 CntPhi = CountPhi;
495 Var = T;
496 }
497
498 return true;
499}
500
501void NclPopcountRecognize::transform(Instruction *CntInst,
502 PHINode *CntPhi, Value *Var) {
503
504 ScalarEvolution *SE = LIR.getScalarEvolution();
505 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
506 BasicBlock *PreHead = CurLoop->getLoopPreheader();
507 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
508 const DebugLoc DL = CntInst->getDebugLoc();
509
510 // Assuming before transformation, the loop is following:
511 // if (x) // the precondition
512 // do { cnt++; x &= x - 1; } while(x);
Matt Arsenaultfb183232013-07-22 18:59:58 +0000513
Shuxin Yang95de7c32012-12-09 03:12:46 +0000514 // Step 1: Insert the ctpop instruction at the end of the precondition block
515 IRBuilderTy Builder(PreCondBr);
516 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
517 {
518 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
519 NewCount = PopCntZext =
520 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
521
522 if (NewCount != PopCnt)
523 (cast<Instruction>(NewCount))->setDebugLoc(DL);
524
525 // TripCnt is exactly the number of iterations the loop has
526 TripCnt = NewCount;
527
Alp Tokercb402912014-01-24 17:20:08 +0000528 // If the population counter's initial value is not zero, insert Add Inst.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000529 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
530 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
531 if (!InitConst || !InitConst->isZero()) {
532 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
533 (cast<Instruction>(NewCount))->setDebugLoc(DL);
534 }
535 }
536
537 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
538 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
539 // function would be partial dead code, and downstream passes will drag
540 // it back from the precondition block to the preheader.
541 {
542 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
543
544 Value *Opnd0 = PopCntZext;
545 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
546 if (PreCond->getOperand(0) != Var)
547 std::swap(Opnd0, Opnd1);
548
549 ICmpInst *NewPreCond =
550 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
551 PreCond->replaceAllUsesWith(NewPreCond);
552
553 deleteDeadInstruction(PreCond, *SE, TLI);
554 }
555
556 // Step 3: Note that the population count is exactly the trip count of the
557 // loop in question, which enble us to to convert the loop from noncountable
558 // loop into a countable one. The benefit is twofold:
559 //
560 // - If the loop only counts population, the entire loop become dead after
561 // the transformation. It is lots easier to prove a countable loop dead
562 // than to prove a noncountable one. (In some C dialects, a infite loop
563 // isn't dead even if it computes nothing useful. In general, DCE needs
564 // to prove a noncountable loop finite before safely delete it.)
565 //
566 // - If the loop also performs something else, it remains alive.
567 // Since it is transformed to countable form, it can be aggressively
568 // optimized by some optimizations which are in general not applicable
569 // to a noncountable loop.
570 //
571 // After this step, this loop (conceptually) would look like following:
572 // newcnt = __builtin_ctpop(x);
573 // t = newcnt;
574 // if (x)
575 // do { cnt++; x &= x-1; t--) } while (t > 0);
576 BasicBlock *Body = *(CurLoop->block_begin());
577 {
578 BranchInst *LbBr = LIRUtil::getBranch(Body);
579 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
580 Type *Ty = TripCnt->getType();
581
582 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
583
584 Builder.SetInsertPoint(LbCond);
585 Value *Opnd1 = cast<Value>(TcPhi);
586 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
587 Instruction *TcDec =
588 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
589
590 TcPhi->addIncoming(TripCnt, PreHead);
591 TcPhi->addIncoming(TcDec, Body);
592
593 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
594 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
595 LbCond->setPredicate(Pred);
596 LbCond->setOperand(0, TcDec);
597 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
598 }
599
600 // Step 4: All the references to the original population counter outside
601 // the loop are replaced with the NewCount -- the value returned from
602 // __builtin_ctpop().
603 {
604 SmallVector<Value *, 4> CntUses;
605 for (Value::use_iterator I = CntInst->use_begin(), E = CntInst->use_end();
606 I != E; I++) {
607 if (cast<Instruction>(*I)->getParent() != Body)
608 CntUses.push_back(*I);
609 }
610 for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
611 (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
612 }
613 }
614
615 // step 5: Forget the "non-computable" trip-count SCEV associated with the
616 // loop. The loop would otherwise not be deleted even if it becomes empty.
617 SE->forgetLoop(CurLoop);
618}
619
Matt Arsenaultfb183232013-07-22 18:59:58 +0000620CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000621 Value *Val, DebugLoc DL) {
622 Value *Ops[] = { Val };
623 Type *Tys[] = { Val->getType() };
624
625 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
626 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
627 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
628 CI->setDebugLoc(DL);
629
630 return CI;
631}
632
633/// recognize - detect population count idiom in a non-countable loop. If
634/// detected, transform the relevant code to popcount intrinsic function
635/// call, and return true; otherwise, return false.
636bool NclPopcountRecognize::recognize() {
637
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000638 if (!LIR.getTargetTransformInfo())
Shuxin Yang95de7c32012-12-09 03:12:46 +0000639 return false;
640
641 LIR.getScalarEvolution();
642
643 if (!preliminaryScreen())
644 return false;
645
646 Instruction *CntInst;
647 PHINode *CntPhi;
648 Value *Val;
649 if (!detectIdiom(CntInst, CntPhi, Val))
650 return false;
651
652 transform(CntInst, CntPhi, Val);
653 return true;
654}
655
656//===----------------------------------------------------------------------===//
657//
658// Implementation of LoopIdiomRecognize
659//
660//===----------------------------------------------------------------------===//
661
662bool LoopIdiomRecognize::runOnCountableLoop() {
663 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
664 if (isa<SCEVCouldNotCompute>(BECount)) return false;
665
666 // If this loop executes exactly one time, then it should be peeled, not
667 // optimized by this pass.
668 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
669 if (BECst->getValue()->getValue() == 0)
670 return false;
671
672 // We require target data for now.
673 if (!getDataLayout())
674 return false;
675
Matt Arsenaultfb183232013-07-22 18:59:58 +0000676 // set DT
Shuxin Yang98c844f2013-01-02 18:26:31 +0000677 (void)getDominatorTree();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000678
679 LoopInfo &LI = getAnalysis<LoopInfo>();
680 TLI = &getAnalysis<TargetLibraryInfo>();
681
Matt Arsenaultfb183232013-07-22 18:59:58 +0000682 // set TLI
Shuxin Yang98c844f2013-01-02 18:26:31 +0000683 (void)getTargetLibraryInfo();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000684
685 SmallVector<BasicBlock*, 8> ExitBlocks;
686 CurLoop->getUniqueExitBlocks(ExitBlocks);
687
688 DEBUG(dbgs() << "loop-idiom Scanning: F["
689 << CurLoop->getHeader()->getParent()->getName()
690 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
691
692 bool MadeChange = false;
693 // Scan all the blocks in the loop that are not in subloops.
694 for (Loop::block_iterator BI = CurLoop->block_begin(),
695 E = CurLoop->block_end(); BI != E; ++BI) {
696 // Ignore blocks in subloops.
697 if (LI.getLoopFor(*BI) != CurLoop)
698 continue;
699
700 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
701 }
702 return MadeChange;
703}
704
705bool LoopIdiomRecognize::runOnNoncountableLoop() {
706 NclPopcountRecognize Popcount(*this);
707 if (Popcount.recognize())
708 return true;
709
710 return false;
711}
712
Chris Lattner81ae3f22010-12-26 19:39:38 +0000713bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000714 if (skipOptnoneFunction(L))
715 return false;
716
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000717 CurLoop = L;
Andrew Trick328b2232011-03-14 16:48:10 +0000718
Benjamin Kramereba9aca2012-09-21 17:27:23 +0000719 // If the loop could not be converted to canonical form, it must have an
720 // indirectbr in it, just give up.
721 if (!L->getLoopPreheader())
722 return false;
723
Nadav Rotem465834c2012-07-24 10:51:42 +0000724 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosiera7ff5432011-07-15 18:25:04 +0000725 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000726 if (Name == "memset" || Name == "memcpy")
Chad Rosiera7ff5432011-07-15 18:25:04 +0000727 return false;
728
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000729 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000730 if (SE->hasLoopInvariantBackedgeTakenCount(L))
731 return runOnCountableLoop();
732 return runOnNoncountableLoop();
Chris Lattner8455b6e2011-01-02 19:01:03 +0000733}
734
735/// runOnLoopBlock - Process the specified block, which lives in a counted loop
736/// with the specified backedge count. This block is known to be in the current
737/// loop and not in any subloops.
738bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
739 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
740 // We can only promote stores in this block if they are unconditionally
741 // executed in the loop. For a block to be unconditionally executed, it has
742 // to dominate all the exit blocks of the loop. Verify this now.
743 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
744 if (!DT->dominates(BB, ExitBlocks[i]))
745 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000746
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000747 bool MadeChange = false;
748 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000749 Instruction *Inst = I++;
750 // Look for store instructions, which may be optimized to memset/memcpy.
751 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000752 WeakVH InstPtr(I);
753 if (!processLoopStore(SI, BECount)) continue;
754 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000755
Chris Lattnera62b01d2011-01-04 07:27:30 +0000756 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000757 // top of the block.
Chris Lattnera62b01d2011-01-04 07:27:30 +0000758 if (InstPtr == 0)
759 I = BB->begin();
760 continue;
761 }
Andrew Trick328b2232011-03-14 16:48:10 +0000762
Chris Lattner86438102011-01-04 07:46:33 +0000763 // Look for memset instructions, which may be optimized to a larger memset.
764 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
765 WeakVH InstPtr(I);
766 if (!processLoopMemSet(MSI, BECount)) continue;
767 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000768
Chris Lattner86438102011-01-04 07:46:33 +0000769 // If processing the memset invalidated our iterator, start over from the
770 // top of the block.
771 if (InstPtr == 0)
772 I = BB->begin();
773 continue;
774 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000775 }
Andrew Trick328b2232011-03-14 16:48:10 +0000776
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000777 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000778}
779
Chris Lattner8455b6e2011-01-02 19:01:03 +0000780
Chris Lattner86438102011-01-04 07:46:33 +0000781/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000782bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman7c5dc122011-09-12 20:23:13 +0000783 if (!SI->isSimple()) return false;
Chris Lattner86438102011-01-04 07:46:33 +0000784
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000785 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000786 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000787
Chris Lattner65a699d2010-12-28 18:53:48 +0000788 // Reject stores that are so large that they overflow an unsigned.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000789 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000790 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000791 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000792
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000793 // See if the pointer expression is an AddRec like {base,+,1} on the current
794 // loop, which indicates a strided store. If we have something else, it's a
795 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000796 const SCEVAddRecExpr *StoreEv =
797 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
798 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000799 return false;
800
801 // Check to see if the stride matches the size of the store. If so, then we
802 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000803 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000804 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000805
Chris Lattnerbc661d62011-02-21 02:08:54 +0000806 if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
807 // TODO: Could also handle negative stride here someday, that will require
808 // the validity check in mayLoopAccessLocation to be updated though.
809 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000810 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000811 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
812 dbgs() << "BB: " << *SI->getParent();
813 }
Andrew Trick328b2232011-03-14 16:48:10 +0000814
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000815 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000816 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000817
818 // See if we can optimize just this store in isolation.
819 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
820 StoredVal, SI, StoreEv, BECount))
821 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000822
Chris Lattner85b6d812011-01-02 03:37:56 +0000823 // If the stored value is a strided load in the same loop with the same stride
824 // this this may be transformable into a memcpy. This kicks in for stuff like
825 // for (i) A[i] = B[i];
826 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
827 const SCEVAddRecExpr *LoadEv =
828 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
829 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000830 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000831 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
832 return true;
833 }
Chris Lattner12f91be2011-01-02 07:36:44 +0000834 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000835
Chris Lattner81ae3f22010-12-26 19:39:38 +0000836 return false;
837}
838
Chris Lattner86438102011-01-04 07:46:33 +0000839/// processLoopMemSet - See if this memset can be promoted to a large memset.
840bool LoopIdiomRecognize::
841processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
842 // We can only handle non-volatile memsets with a constant size.
843 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
844
Chris Lattnere6b261f2011-02-18 22:22:15 +0000845 // If we're not allowed to hack on memset, we fail.
846 if (!TLI->has(LibFunc::memset))
847 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000848
Chris Lattner86438102011-01-04 07:46:33 +0000849 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000850
Chris Lattner86438102011-01-04 07:46:33 +0000851 // See if the pointer expression is an AddRec like {base,+,1} on the current
852 // loop, which indicates a strided store. If we have something else, it's a
853 // random store we can't handle.
854 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
855 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
856 return false;
857
858 // Reject memsets that are so large that they overflow an unsigned.
859 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
860 if ((SizeInBytes >> 32) != 0)
861 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000862
Chris Lattner86438102011-01-04 07:46:33 +0000863 // Check to see if the stride matches the size of the memset. If so, then we
864 // know that every byte is touched in the loop.
865 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000866
Chris Lattner86438102011-01-04 07:46:33 +0000867 // TODO: Could also handle negative stride here someday, that will require the
868 // validity check in mayLoopAccessLocation to be updated though.
869 if (Stride == 0 || MSI->getLength() != Stride->getValue())
870 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000871
Chris Lattner0f4a6402011-02-19 19:31:39 +0000872 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
873 MSI->getAlignment(), MSI->getValue(),
874 MSI, Ev, BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000875}
876
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000877
878/// mayLoopAccessLocation - Return true if the specified loop might access the
879/// specified pointer location, which is a loop-strided access. The 'Access'
880/// argument specifies what the verboten forms of access are (read or write).
881static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
882 Loop *L, const SCEV *BECount,
883 unsigned StoreSize, AliasAnalysis &AA,
884 Instruction *IgnoredStore) {
885 // Get the location that may be stored across the loop. Since the access is
886 // strided positively through memory, we say that the modified location starts
887 // at the pointer and has infinite size.
888 uint64_t AccessSize = AliasAnalysis::UnknownSize;
889
890 // If the loop iterates a fixed number of times, we can refine the access size
891 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
892 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
893 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
894
895 // TODO: For this to be really effective, we have to dive into the pointer
896 // operand in the store. Store to &A[i] of 100 will always return may alias
897 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
898 // which will then no-alias a store to &A[100].
899 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
900
901 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
902 ++BI)
903 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
904 if (&*I != IgnoredStore &&
905 (AA.getModRefInfo(I, StoreLoc) & Access))
906 return true;
907
908 return false;
909}
910
Chris Lattner0f4a6402011-02-19 19:31:39 +0000911/// getMemSetPatternValue - If a strided store of the specified value is safe to
912/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
913/// be passed in. Otherwise, return null.
914///
915/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
916/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000917static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000918 // If the value isn't a constant, we can't promote it to being in a constant
919 // array. We could theoretically do a store to an alloca or something, but
920 // that doesn't seem worthwhile.
921 Constant *C = dyn_cast<Constant>(V);
922 if (C == 0) return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000923
Chris Lattner0f4a6402011-02-19 19:31:39 +0000924 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000925 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chris Lattner0f4a6402011-02-19 19:31:39 +0000926 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
927 return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000928
Chris Lattner72a35fb2011-02-19 19:56:44 +0000929 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000930 if (DL.isBigEndian())
Chris Lattner72a35fb2011-02-19 19:56:44 +0000931 return 0;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000932
933 // Convert to size in bytes.
934 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000935
Chris Lattner0f4a6402011-02-19 19:31:39 +0000936 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000937 // if the top and bottom are the same (e.g. for vectors and large integers).
Chris Lattner0f4a6402011-02-19 19:31:39 +0000938 if (Size > 16) return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000939
Chris Lattner72a35fb2011-02-19 19:56:44 +0000940 // If the constant is exactly 16 bytes, just use it.
941 if (Size == 16) return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000942
Chris Lattner72a35fb2011-02-19 19:56:44 +0000943 // Otherwise, we'll use an array of the constants.
944 unsigned ArraySize = 16/Size;
945 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
946 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000947}
948
949
950/// processLoopStridedStore - We see a strided store of some value. If we can
951/// transform this into a memset or memset_pattern in the loop preheader, do so.
952bool LoopIdiomRecognize::
953processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
954 unsigned StoreAlignment, Value *StoredVal,
955 Instruction *TheStore, const SCEVAddRecExpr *Ev,
956 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000957
Chris Lattner0f4a6402011-02-19 19:31:39 +0000958 // If the stored value is a byte-wise value (like i32 -1), then it may be
959 // turned into a memset of i8 -1, assuming that all the consecutive bytes
960 // are stored. A store of i32 0x01020304 can never be turned into a memset,
961 // but it can be turned into memset_pattern if the target supports it.
962 Value *SplatValue = isBytewiseValue(StoredVal);
963 Constant *PatternValue = 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000964
Matt Arsenault009faed2013-09-11 05:09:42 +0000965 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
966
Chris Lattner0f4a6402011-02-19 19:31:39 +0000967 // If we're allowed to form a memset, and the stored value would be acceptable
968 // for memset, use it.
969 if (SplatValue && TLI->has(LibFunc::memset) &&
970 // Verify that the stored value is loop invariant. If not, we can't
971 // promote the memset.
972 CurLoop->isLoopInvariant(SplatValue)) {
973 // Keep and use SplatValue.
974 PatternValue = 0;
Matt Arsenault009faed2013-09-11 05:09:42 +0000975 } else if (DestAS == 0 &&
976 TLI->has(LibFunc::memset_pattern16) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000977 (PatternValue = getMemSetPatternValue(StoredVal, *DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000978 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000979 // It looks like we can use PatternValue!
980 SplatValue = 0;
981 } else {
982 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000983 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000984 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000985 }
Andrew Trick328b2232011-03-14 16:48:10 +0000986
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000987 // The trip count of the loop and the base pointer of the addrec SCEV is
988 // guaranteed to be loop invariant, which means that it should dominate the
989 // header. This allows us to insert code for it in the preheader.
990 BasicBlock *Preheader = CurLoop->getLoopPreheader();
991 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick411daa52011-06-28 05:07:32 +0000992 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000993
Matt Arsenault009faed2013-09-11 05:09:42 +0000994 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
995
Chris Lattner29e14ed2010-12-26 23:42:51 +0000996 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000997 // this into a memset in the loop preheader now if we want. However, this
998 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000999 // or write to the aliased location. Check for any overlap by generating the
1000 // base pointer and checking the region.
Andrew Trick328b2232011-03-14 16:48:10 +00001001 Value *BasePtr =
Matt Arsenault009faed2013-09-11 05:09:42 +00001002 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
Chris Lattner29e14ed2010-12-26 23:42:51 +00001003 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001004
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001005 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
1006 CurLoop, BECount,
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001007 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001008 Expander.clear();
1009 // If we generated new code for the base pointer, clean up.
1010 deleteIfDeadInstruction(BasePtr, *SE, TLI);
1011 return false;
1012 }
1013
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001014 // Okay, everything looks good, insert the memset.
1015
Chris Lattner29e14ed2010-12-26 23:42:51 +00001016 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1017 // pointer size if it isn't already.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001018 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +00001019 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +00001020
Chris Lattner29e14ed2010-12-26 23:42:51 +00001021 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +00001022 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001023 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +00001024 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001025 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001026 }
Andrew Trick328b2232011-03-14 16:48:10 +00001027
1028 Value *NumBytes =
Chris Lattner29e14ed2010-12-26 23:42:51 +00001029 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001030
Devang Pateld00c6282011-03-07 22:43:45 +00001031 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001032 if (SplatValue) {
1033 NewCall = Builder.CreateMemSet(BasePtr,
1034 SplatValue,
1035 NumBytes,
1036 StoreAlignment);
1037 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +00001038 // Everything is emitted in default address space
1039 Type *Int8PtrTy = DestInt8PtrTy;
1040
Chris Lattner0f4a6402011-02-19 19:31:39 +00001041 Module *M = TheStore->getParent()->getParent()->getParent();
1042 Value *MSP = M->getOrInsertFunction("memset_pattern16",
1043 Builder.getVoidTy(),
Matt Arsenault009faed2013-09-11 05:09:42 +00001044 Int8PtrTy,
1045 Int8PtrTy,
1046 IntPtr,
Chris Lattner0f4a6402011-02-19 19:31:39 +00001047 (void*)0);
Andrew Trick328b2232011-03-14 16:48:10 +00001048
Chris Lattner0f4a6402011-02-19 19:31:39 +00001049 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1050 // an constant array of 16-bytes. Plop the value into a mergable global.
1051 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1052 GlobalValue::InternalLinkage,
1053 PatternValue, ".memset_pattern");
1054 GV->setUnnamedAddr(true); // Ok to merge these.
1055 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +00001056 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
Chris Lattner0f4a6402011-02-19 19:31:39 +00001057 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1058 }
Andrew Trick328b2232011-03-14 16:48:10 +00001059
Chris Lattner29e14ed2010-12-26 23:42:51 +00001060 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +00001061 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +00001062 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001063
Chris Lattnerb9fe6852010-12-27 00:03:23 +00001064 // Okay, the memset has been formed. Zap the original store and anything that
1065 // feeds into it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001066 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +00001067 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +00001068 return true;
1069}
1070
Chris Lattner85b6d812011-01-02 03:37:56 +00001071/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1072/// same-strided load.
1073bool LoopIdiomRecognize::
1074processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1075 const SCEVAddRecExpr *StoreEv,
1076 const SCEVAddRecExpr *LoadEv,
1077 const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +00001078 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001079 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +00001080 return false;
Andrew Trick328b2232011-03-14 16:48:10 +00001081
Chris Lattner85b6d812011-01-02 03:37:56 +00001082 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +00001083
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001084 // The trip count of the loop and the base pointer of the addrec SCEV is
1085 // guaranteed to be loop invariant, which means that it should dominate the
1086 // header. This allows us to insert code for it in the preheader.
1087 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1088 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick411daa52011-06-28 05:07:32 +00001089 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001090
Chris Lattner85b6d812011-01-02 03:37:56 +00001091 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001092 // this into a memcpy in the loop preheader now if we want. However, this
1093 // would be unsafe to do if there is anything else in the loop that may read
1094 // or write the memory region we're storing to. This includes the load that
1095 // feeds the stores. Check for an alias by generating the base address and
1096 // checking everything.
Andrew Trick328b2232011-03-14 16:48:10 +00001097 Value *StoreBasePtr =
Chris Lattner85b6d812011-01-02 03:37:56 +00001098 Expander.expandCodeFor(StoreEv->getStart(),
1099 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1100 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001101
1102 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1103 CurLoop, BECount, StoreSize,
1104 getAnalysis<AliasAnalysis>(), SI)) {
1105 Expander.clear();
1106 // If we generated new code for the base pointer, clean up.
1107 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1108 return false;
1109 }
1110
1111 // For a memcpy, we have to make sure that the input array is not being
1112 // mutated by the loop.
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001113 Value *LoadBasePtr =
1114 Expander.expandCodeFor(LoadEv->getStart(),
1115 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1116 Preheader->getTerminator());
1117
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001118 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1119 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1120 Expander.clear();
1121 // If we generated new code for the base pointer, clean up.
1122 deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1123 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1124 return false;
1125 }
1126
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001127 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001128
Andrew Trick328b2232011-03-14 16:48:10 +00001129
Chris Lattner85b6d812011-01-02 03:37:56 +00001130 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1131 // pointer size if it isn't already.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001132 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +00001133 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +00001134
Matt Arsenault009faed2013-09-11 05:09:42 +00001135 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +00001136 SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +00001137 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +00001138 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001139 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +00001140
Chris Lattner85b6d812011-01-02 03:37:56 +00001141 Value *NumBytes =
Matt Arsenault009faed2013-09-11 05:09:42 +00001142 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001143
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001144 CallInst *NewCall =
1145 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1146 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +00001147 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001148
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001149 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001150 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1151 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001152
Andrew Trick328b2232011-03-14 16:48:10 +00001153
Chris Lattner85b6d812011-01-02 03:37:56 +00001154 // Okay, the memset has been formed. Zap the original store and anything that
1155 // feeds into it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001156 deleteDeadInstruction(SI, *SE, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001157 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001158 return true;
1159}