blob: 5557463386bcfedbd2d644bbfd34b3a310e75cff [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
112 /// beween a variable and zero, and if the variable is non-zero, the
113 /// control yeilds to the loop entry. If the branch matches the behavior,
114 /// 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;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000135 const DataLayout *TD;
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());
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000144 TD = 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>();
178 AU.addPreserved<DominatorTree>();
Chris Lattner8455b6e2011-01-02 19:01:03 +0000179 AU.addRequired<DominatorTree>();
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() {
185 return TD ? TD : TD=getAnalysisIfAvailable<DataLayout>();
186 }
187
188 DominatorTree *getDominatorTree() {
189 return DT ? DT : (DT=&getAnalysis<DominatorTree>());
190 }
191
192 ScalarEvolution *getScalarEvolution() {
193 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
194 }
195
196 TargetLibraryInfo *getTargetLibraryInfo() {
197 return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
198 }
199
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000200 const TargetTransformInfo *getTargetTransformInfo() {
Chandler Carruth342cc252013-01-07 09:17:41 +0000201 return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000202 }
203
204 Loop *getLoop() const { return CurLoop; }
205
206 private:
207 bool runOnNoncountableLoop();
208 bool runOnCountableLoop();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000209 };
210}
211
212char LoopIdiomRecognize::ID = 0;
213INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
214 false, false)
215INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner8455b6e2011-01-02 19:01:03 +0000216INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000217INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
218INITIALIZE_PASS_DEPENDENCY(LCSSA)
219INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000220INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000221INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth342cc252013-01-07 09:17:41 +0000222INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000223INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
224 false, false)
225
226Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
227
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000228/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000229/// and zero out all the operands of this instruction. If any of them become
230/// dead, delete them and the computation tree that feeds them.
231///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000232static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
233 const TargetLibraryInfo *TLI) {
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000234 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trick328b2232011-03-14 16:48:10 +0000235
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000236 NowDeadInsts.push_back(I);
Andrew Trick328b2232011-03-14 16:48:10 +0000237
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000238 // Before we touch this instruction, remove it from SE!
239 do {
240 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trick328b2232011-03-14 16:48:10 +0000241
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000242 // This instruction is dead, zap it, in stages. Start by removing it from
243 // SCEV.
244 SE.forgetValue(DeadInst);
Andrew Trick328b2232011-03-14 16:48:10 +0000245
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000246 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
247 Value *Op = DeadInst->getOperand(op);
248 DeadInst->setOperand(op, 0);
Andrew Trick328b2232011-03-14 16:48:10 +0000249
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000250 // If this operand just became dead, add it to the NowDeadInsts list.
251 if (!Op->use_empty()) continue;
Andrew Trick328b2232011-03-14 16:48:10 +0000252
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000253 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000254 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000255 NowDeadInsts.push_back(OpI);
256 }
Andrew Trick328b2232011-03-14 16:48:10 +0000257
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000258 DeadInst->eraseFromParent();
Andrew Trick328b2232011-03-14 16:48:10 +0000259
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000260 } while (!NowDeadInsts.empty());
261}
262
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000263/// deleteIfDeadInstruction - If the specified value is a dead instruction,
264/// delete it and any recursively used instructions.
265static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
266 const TargetLibraryInfo *TLI) {
267 if (Instruction *I = dyn_cast<Instruction>(V))
268 if (isInstructionTriviallyDead(I, TLI))
269 deleteDeadInstruction(I, SE, TLI);
270}
271
Shuxin Yang95de7c32012-12-09 03:12:46 +0000272//===----------------------------------------------------------------------===//
273//
274// Implementation of LIRUtil
275//
276//===----------------------------------------------------------------------===//
277
Matt Arsenaultfb183232013-07-22 18:59:58 +0000278// This function will return true iff the given block contains nothing but goto.
279// A typical usage of this function is to check if the preheader function is
280// "almost" empty such that generated intrinsic functions can be moved across
281// the preheader and be placed at the end of the precondition block without
282// the concern of breaking data dependence.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000283bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
284 if (BranchInst *Br = getBranch(BB)) {
285 return Br->isUnconditional() && BB->size() == 1;
286 }
287 return false;
288}
289
290Value *LIRUtil::getBrCondtion(BasicBlock *BB) {
291 BranchInst *Br = getBranch(BB);
292 return Br ? Br->getCondition() : 0;
293}
294
295BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
296 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
297 BranchInst *Br = getBranch(BB);
298 return Br && Br->isConditional() ? BB : 0;
299 }
300 return 0;
301}
302
303//===----------------------------------------------------------------------===//
304//
305// Implementation of NclPopcountRecognize
306//
307//===----------------------------------------------------------------------===//
308
309NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
310 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(0) {
311}
312
313bool NclPopcountRecognize::preliminaryScreen() {
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000314 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
Chandler Carruth50a36cd2013-01-07 03:16:03 +0000315 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000316 return false;
317
Robert Wilhelm2788d3e2013-09-28 13:42:22 +0000318 // Counting population are usually conducted by few arithmetic instructions.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000319 // Such instructions can be easilly "absorbed" by vacant slots in a
320 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
321 // in a compact loop.
322
323 // Give up if the loop has multiple blocks or multiple backedges.
324 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
325 return false;
326
327 BasicBlock *LoopBody = *(CurLoop->block_begin());
328 if (LoopBody->size() >= 20) {
329 // The loop is too big, bail out.
330 return false;
331 }
332
333 // It should have a preheader containing nothing but a goto instruction.
334 BasicBlock *PreHead = CurLoop->getLoopPreheader();
335 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
336 return false;
337
338 // It should have a precondition block where the generated popcount instrinsic
339 // function will be inserted.
340 PreCondBB = LIRUtil::getPrecondBb(PreHead);
341 if (!PreCondBB)
342 return false;
Matt Arsenaultfb183232013-07-22 18:59:58 +0000343
Shuxin Yang95de7c32012-12-09 03:12:46 +0000344 return true;
345}
346
347Value *NclPopcountRecognize::matchCondition (BranchInst *Br,
348 BasicBlock *LoopEntry) const {
349 if (!Br || !Br->isConditional())
350 return 0;
351
352 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
353 if (!Cond)
354 return 0;
355
356 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
357 if (!CmpZero || !CmpZero->isZero())
358 return 0;
359
360 ICmpInst::Predicate Pred = Cond->getPredicate();
361 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
362 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
363 return Cond->getOperand(0);
364
365 return 0;
366}
367
368bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
369 PHINode *&CntPhi,
370 Value *&Var) const {
371 // Following code tries to detect this idiom:
372 //
373 // if (x0 != 0)
374 // goto loop-exit // the precondition of the loop
375 // cnt0 = init-val;
376 // do {
377 // x1 = phi (x0, x2);
378 // cnt1 = phi(cnt0, cnt2);
379 //
380 // cnt2 = cnt1 + 1;
381 // ...
382 // x2 = x1 & (x1 - 1);
383 // ...
384 // } while(x != 0);
385 //
386 // loop-exit:
387 //
388
389 // step 1: Check to see if the look-back branch match this pattern:
390 // "if (a!=0) goto loop-entry".
391 BasicBlock *LoopEntry;
392 Instruction *DefX2, *CountInst;
393 Value *VarX1, *VarX0;
394 PHINode *PhiX, *CountPhi;
395
396 DefX2 = CountInst = 0;
397 VarX1 = VarX0 = 0;
398 PhiX = CountPhi = 0;
399 LoopEntry = *(CurLoop->block_begin());
400
401 // step 1: Check if the loop-back branch is in desirable form.
402 {
403 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
404 DefX2 = dyn_cast<Instruction>(T);
405 else
406 return false;
407 }
408
409 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
410 {
Shuxin Yangc5c730b2013-01-10 23:32:01 +0000411 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000412 return false;
413
414 BinaryOperator *SubOneOp;
415
416 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
417 VarX1 = DefX2->getOperand(1);
418 else {
419 VarX1 = DefX2->getOperand(0);
420 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
421 }
422 if (!SubOneOp)
423 return false;
424
425 Instruction *SubInst = cast<Instruction>(SubOneOp);
426 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
427 if (!Dec ||
428 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
429 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
430 return false;
431 }
432 }
433
434 // step 3: Check the recurrence of variable X
435 {
436 PhiX = dyn_cast<PHINode>(VarX1);
437 if (!PhiX ||
438 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
439 return false;
440 }
441 }
442
443 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
444 {
445 CountInst = NULL;
446 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
447 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
448 Instruction *Inst = Iter;
449 if (Inst->getOpcode() != Instruction::Add)
450 continue;
451
452 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
453 if (!Inc || !Inc->isOne())
454 continue;
455
456 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
457 if (!Phi || Phi->getParent() != LoopEntry)
458 continue;
459
460 // Check if the result of the instruction is live of the loop.
461 bool LiveOutLoop = false;
462 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
463 I != E; I++) {
464 if ((cast<Instruction>(*I))->getParent() != LoopEntry) {
465 LiveOutLoop = true; break;
466 }
467 }
468
469 if (LiveOutLoop) {
470 CountInst = Inst;
471 CountPhi = Phi;
472 break;
473 }
474 }
475
476 if (!CountInst)
477 return false;
478 }
479
480 // step 5: check if the precondition is in this form:
481 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
482 {
483 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
484 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
485 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
486 return false;
487
488 CntInst = CountInst;
489 CntPhi = CountPhi;
490 Var = T;
491 }
492
493 return true;
494}
495
496void NclPopcountRecognize::transform(Instruction *CntInst,
497 PHINode *CntPhi, Value *Var) {
498
499 ScalarEvolution *SE = LIR.getScalarEvolution();
500 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
501 BasicBlock *PreHead = CurLoop->getLoopPreheader();
502 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
503 const DebugLoc DL = CntInst->getDebugLoc();
504
505 // Assuming before transformation, the loop is following:
506 // if (x) // the precondition
507 // do { cnt++; x &= x - 1; } while(x);
Matt Arsenaultfb183232013-07-22 18:59:58 +0000508
Shuxin Yang95de7c32012-12-09 03:12:46 +0000509 // Step 1: Insert the ctpop instruction at the end of the precondition block
510 IRBuilderTy Builder(PreCondBr);
511 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
512 {
513 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
514 NewCount = PopCntZext =
515 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
516
517 if (NewCount != PopCnt)
518 (cast<Instruction>(NewCount))->setDebugLoc(DL);
519
520 // TripCnt is exactly the number of iterations the loop has
521 TripCnt = NewCount;
522
523 // If the popoulation counter's initial value is not zero, insert Add Inst.
524 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
525 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
526 if (!InitConst || !InitConst->isZero()) {
527 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
528 (cast<Instruction>(NewCount))->setDebugLoc(DL);
529 }
530 }
531
532 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
533 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
534 // function would be partial dead code, and downstream passes will drag
535 // it back from the precondition block to the preheader.
536 {
537 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
538
539 Value *Opnd0 = PopCntZext;
540 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
541 if (PreCond->getOperand(0) != Var)
542 std::swap(Opnd0, Opnd1);
543
544 ICmpInst *NewPreCond =
545 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
546 PreCond->replaceAllUsesWith(NewPreCond);
547
548 deleteDeadInstruction(PreCond, *SE, TLI);
549 }
550
551 // Step 3: Note that the population count is exactly the trip count of the
552 // loop in question, which enble us to to convert the loop from noncountable
553 // loop into a countable one. The benefit is twofold:
554 //
555 // - If the loop only counts population, the entire loop become dead after
556 // the transformation. It is lots easier to prove a countable loop dead
557 // than to prove a noncountable one. (In some C dialects, a infite loop
558 // isn't dead even if it computes nothing useful. In general, DCE needs
559 // to prove a noncountable loop finite before safely delete it.)
560 //
561 // - If the loop also performs something else, it remains alive.
562 // Since it is transformed to countable form, it can be aggressively
563 // optimized by some optimizations which are in general not applicable
564 // to a noncountable loop.
565 //
566 // After this step, this loop (conceptually) would look like following:
567 // newcnt = __builtin_ctpop(x);
568 // t = newcnt;
569 // if (x)
570 // do { cnt++; x &= x-1; t--) } while (t > 0);
571 BasicBlock *Body = *(CurLoop->block_begin());
572 {
573 BranchInst *LbBr = LIRUtil::getBranch(Body);
574 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
575 Type *Ty = TripCnt->getType();
576
577 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
578
579 Builder.SetInsertPoint(LbCond);
580 Value *Opnd1 = cast<Value>(TcPhi);
581 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
582 Instruction *TcDec =
583 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
584
585 TcPhi->addIncoming(TripCnt, PreHead);
586 TcPhi->addIncoming(TcDec, Body);
587
588 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
589 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
590 LbCond->setPredicate(Pred);
591 LbCond->setOperand(0, TcDec);
592 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
593 }
594
595 // Step 4: All the references to the original population counter outside
596 // the loop are replaced with the NewCount -- the value returned from
597 // __builtin_ctpop().
598 {
599 SmallVector<Value *, 4> CntUses;
600 for (Value::use_iterator I = CntInst->use_begin(), E = CntInst->use_end();
601 I != E; I++) {
602 if (cast<Instruction>(*I)->getParent() != Body)
603 CntUses.push_back(*I);
604 }
605 for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
606 (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
607 }
608 }
609
610 // step 5: Forget the "non-computable" trip-count SCEV associated with the
611 // loop. The loop would otherwise not be deleted even if it becomes empty.
612 SE->forgetLoop(CurLoop);
613}
614
Matt Arsenaultfb183232013-07-22 18:59:58 +0000615CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000616 Value *Val, DebugLoc DL) {
617 Value *Ops[] = { Val };
618 Type *Tys[] = { Val->getType() };
619
620 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
621 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
622 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
623 CI->setDebugLoc(DL);
624
625 return CI;
626}
627
628/// recognize - detect population count idiom in a non-countable loop. If
629/// detected, transform the relevant code to popcount intrinsic function
630/// call, and return true; otherwise, return false.
631bool NclPopcountRecognize::recognize() {
632
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000633 if (!LIR.getTargetTransformInfo())
Shuxin Yang95de7c32012-12-09 03:12:46 +0000634 return false;
635
636 LIR.getScalarEvolution();
637
638 if (!preliminaryScreen())
639 return false;
640
641 Instruction *CntInst;
642 PHINode *CntPhi;
643 Value *Val;
644 if (!detectIdiom(CntInst, CntPhi, Val))
645 return false;
646
647 transform(CntInst, CntPhi, Val);
648 return true;
649}
650
651//===----------------------------------------------------------------------===//
652//
653// Implementation of LoopIdiomRecognize
654//
655//===----------------------------------------------------------------------===//
656
657bool LoopIdiomRecognize::runOnCountableLoop() {
658 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
659 if (isa<SCEVCouldNotCompute>(BECount)) return false;
660
661 // If this loop executes exactly one time, then it should be peeled, not
662 // optimized by this pass.
663 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
664 if (BECst->getValue()->getValue() == 0)
665 return false;
666
667 // We require target data for now.
668 if (!getDataLayout())
669 return false;
670
Matt Arsenaultfb183232013-07-22 18:59:58 +0000671 // set DT
Shuxin Yang98c844f2013-01-02 18:26:31 +0000672 (void)getDominatorTree();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000673
674 LoopInfo &LI = getAnalysis<LoopInfo>();
675 TLI = &getAnalysis<TargetLibraryInfo>();
676
Matt Arsenaultfb183232013-07-22 18:59:58 +0000677 // set TLI
Shuxin Yang98c844f2013-01-02 18:26:31 +0000678 (void)getTargetLibraryInfo();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000679
680 SmallVector<BasicBlock*, 8> ExitBlocks;
681 CurLoop->getUniqueExitBlocks(ExitBlocks);
682
683 DEBUG(dbgs() << "loop-idiom Scanning: F["
684 << CurLoop->getHeader()->getParent()->getName()
685 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
686
687 bool MadeChange = false;
688 // Scan all the blocks in the loop that are not in subloops.
689 for (Loop::block_iterator BI = CurLoop->block_begin(),
690 E = CurLoop->block_end(); BI != E; ++BI) {
691 // Ignore blocks in subloops.
692 if (LI.getLoopFor(*BI) != CurLoop)
693 continue;
694
695 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
696 }
697 return MadeChange;
698}
699
700bool LoopIdiomRecognize::runOnNoncountableLoop() {
701 NclPopcountRecognize Popcount(*this);
702 if (Popcount.recognize())
703 return true;
704
705 return false;
706}
707
Chris Lattner81ae3f22010-12-26 19:39:38 +0000708bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000709 CurLoop = L;
Andrew Trick328b2232011-03-14 16:48:10 +0000710
Benjamin Kramereba9aca2012-09-21 17:27:23 +0000711 // If the loop could not be converted to canonical form, it must have an
712 // indirectbr in it, just give up.
713 if (!L->getLoopPreheader())
714 return false;
715
Nadav Rotem465834c2012-07-24 10:51:42 +0000716 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosiera7ff5432011-07-15 18:25:04 +0000717 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000718 if (Name == "memset" || Name == "memcpy")
Chad Rosiera7ff5432011-07-15 18:25:04 +0000719 return false;
720
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000721 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000722 if (SE->hasLoopInvariantBackedgeTakenCount(L))
723 return runOnCountableLoop();
724 return runOnNoncountableLoop();
Chris Lattner8455b6e2011-01-02 19:01:03 +0000725}
726
727/// runOnLoopBlock - Process the specified block, which lives in a counted loop
728/// with the specified backedge count. This block is known to be in the current
729/// loop and not in any subloops.
730bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
731 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
732 // We can only promote stores in this block if they are unconditionally
733 // executed in the loop. For a block to be unconditionally executed, it has
734 // to dominate all the exit blocks of the loop. Verify this now.
735 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
736 if (!DT->dominates(BB, ExitBlocks[i]))
737 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000738
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000739 bool MadeChange = false;
740 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000741 Instruction *Inst = I++;
742 // Look for store instructions, which may be optimized to memset/memcpy.
743 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000744 WeakVH InstPtr(I);
745 if (!processLoopStore(SI, BECount)) continue;
746 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000747
Chris Lattnera62b01d2011-01-04 07:27:30 +0000748 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000749 // top of the block.
Chris Lattnera62b01d2011-01-04 07:27:30 +0000750 if (InstPtr == 0)
751 I = BB->begin();
752 continue;
753 }
Andrew Trick328b2232011-03-14 16:48:10 +0000754
Chris Lattner86438102011-01-04 07:46:33 +0000755 // Look for memset instructions, which may be optimized to a larger memset.
756 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
757 WeakVH InstPtr(I);
758 if (!processLoopMemSet(MSI, BECount)) continue;
759 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000760
Chris Lattner86438102011-01-04 07:46:33 +0000761 // If processing the memset invalidated our iterator, start over from the
762 // top of the block.
763 if (InstPtr == 0)
764 I = BB->begin();
765 continue;
766 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000767 }
Andrew Trick328b2232011-03-14 16:48:10 +0000768
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000769 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000770}
771
Chris Lattner8455b6e2011-01-02 19:01:03 +0000772
Chris Lattner86438102011-01-04 07:46:33 +0000773/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000774bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman7c5dc122011-09-12 20:23:13 +0000775 if (!SI->isSimple()) return false;
Chris Lattner86438102011-01-04 07:46:33 +0000776
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000777 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000778 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000779
Chris Lattner65a699d2010-12-28 18:53:48 +0000780 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000781 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000782 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000783 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000784
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000785 // See if the pointer expression is an AddRec like {base,+,1} on the current
786 // loop, which indicates a strided store. If we have something else, it's a
787 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000788 const SCEVAddRecExpr *StoreEv =
789 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
790 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000791 return false;
792
793 // Check to see if the stride matches the size of the store. If so, then we
794 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000795 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000796 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000797
Chris Lattnerbc661d62011-02-21 02:08:54 +0000798 if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
799 // TODO: Could also handle negative stride here someday, that will require
800 // the validity check in mayLoopAccessLocation to be updated though.
801 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000802 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000803 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
804 dbgs() << "BB: " << *SI->getParent();
805 }
Andrew Trick328b2232011-03-14 16:48:10 +0000806
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000807 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000808 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000809
810 // See if we can optimize just this store in isolation.
811 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
812 StoredVal, SI, StoreEv, BECount))
813 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000814
Chris Lattner85b6d812011-01-02 03:37:56 +0000815 // If the stored value is a strided load in the same loop with the same stride
816 // this this may be transformable into a memcpy. This kicks in for stuff like
817 // for (i) A[i] = B[i];
818 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
819 const SCEVAddRecExpr *LoadEv =
820 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
821 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000822 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000823 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
824 return true;
825 }
Chris Lattner12f91be2011-01-02 07:36:44 +0000826 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000827
Chris Lattner81ae3f22010-12-26 19:39:38 +0000828 return false;
829}
830
Chris Lattner86438102011-01-04 07:46:33 +0000831/// processLoopMemSet - See if this memset can be promoted to a large memset.
832bool LoopIdiomRecognize::
833processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
834 // We can only handle non-volatile memsets with a constant size.
835 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
836
Chris Lattnere6b261f2011-02-18 22:22:15 +0000837 // If we're not allowed to hack on memset, we fail.
838 if (!TLI->has(LibFunc::memset))
839 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000840
Chris Lattner86438102011-01-04 07:46:33 +0000841 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000842
Chris Lattner86438102011-01-04 07:46:33 +0000843 // See if the pointer expression is an AddRec like {base,+,1} on the current
844 // loop, which indicates a strided store. If we have something else, it's a
845 // random store we can't handle.
846 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
847 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
848 return false;
849
850 // Reject memsets that are so large that they overflow an unsigned.
851 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
852 if ((SizeInBytes >> 32) != 0)
853 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000854
Chris Lattner86438102011-01-04 07:46:33 +0000855 // Check to see if the stride matches the size of the memset. If so, then we
856 // know that every byte is touched in the loop.
857 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000858
Chris Lattner86438102011-01-04 07:46:33 +0000859 // TODO: Could also handle negative stride here someday, that will require the
860 // validity check in mayLoopAccessLocation to be updated though.
861 if (Stride == 0 || MSI->getLength() != Stride->getValue())
862 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000863
Chris Lattner0f4a6402011-02-19 19:31:39 +0000864 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
865 MSI->getAlignment(), MSI->getValue(),
866 MSI, Ev, BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000867}
868
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000869
870/// mayLoopAccessLocation - Return true if the specified loop might access the
871/// specified pointer location, which is a loop-strided access. The 'Access'
872/// argument specifies what the verboten forms of access are (read or write).
873static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
874 Loop *L, const SCEV *BECount,
875 unsigned StoreSize, AliasAnalysis &AA,
876 Instruction *IgnoredStore) {
877 // Get the location that may be stored across the loop. Since the access is
878 // strided positively through memory, we say that the modified location starts
879 // at the pointer and has infinite size.
880 uint64_t AccessSize = AliasAnalysis::UnknownSize;
881
882 // If the loop iterates a fixed number of times, we can refine the access size
883 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
884 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
885 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
886
887 // TODO: For this to be really effective, we have to dive into the pointer
888 // operand in the store. Store to &A[i] of 100 will always return may alias
889 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
890 // which will then no-alias a store to &A[100].
891 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
892
893 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
894 ++BI)
895 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
896 if (&*I != IgnoredStore &&
897 (AA.getModRefInfo(I, StoreLoc) & Access))
898 return true;
899
900 return false;
901}
902
Chris Lattner0f4a6402011-02-19 19:31:39 +0000903/// getMemSetPatternValue - If a strided store of the specified value is safe to
904/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
905/// be passed in. Otherwise, return null.
906///
907/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
908/// just replicate their input array and then pass on to memset_pattern16.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000909static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000910 // If the value isn't a constant, we can't promote it to being in a constant
911 // array. We could theoretically do a store to an alloca or something, but
912 // that doesn't seem worthwhile.
913 Constant *C = dyn_cast<Constant>(V);
914 if (C == 0) return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000915
Chris Lattner0f4a6402011-02-19 19:31:39 +0000916 // Only handle simple values that are a power of two bytes in size.
917 uint64_t Size = TD.getTypeSizeInBits(V->getType());
918 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
919 return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000920
Chris Lattner72a35fb2011-02-19 19:56:44 +0000921 // Don't care enough about darwin/ppc to implement this.
922 if (TD.isBigEndian())
923 return 0;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000924
925 // Convert to size in bytes.
926 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000927
Chris Lattner0f4a6402011-02-19 19:31:39 +0000928 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000929 // if the top and bottom are the same (e.g. for vectors and large integers).
Chris Lattner0f4a6402011-02-19 19:31:39 +0000930 if (Size > 16) return 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000931
Chris Lattner72a35fb2011-02-19 19:56:44 +0000932 // If the constant is exactly 16 bytes, just use it.
933 if (Size == 16) return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000934
Chris Lattner72a35fb2011-02-19 19:56:44 +0000935 // Otherwise, we'll use an array of the constants.
936 unsigned ArraySize = 16/Size;
937 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
938 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000939}
940
941
942/// processLoopStridedStore - We see a strided store of some value. If we can
943/// transform this into a memset or memset_pattern in the loop preheader, do so.
944bool LoopIdiomRecognize::
945processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
946 unsigned StoreAlignment, Value *StoredVal,
947 Instruction *TheStore, const SCEVAddRecExpr *Ev,
948 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000949
Chris Lattner0f4a6402011-02-19 19:31:39 +0000950 // If the stored value is a byte-wise value (like i32 -1), then it may be
951 // turned into a memset of i8 -1, assuming that all the consecutive bytes
952 // are stored. A store of i32 0x01020304 can never be turned into a memset,
953 // but it can be turned into memset_pattern if the target supports it.
954 Value *SplatValue = isBytewiseValue(StoredVal);
955 Constant *PatternValue = 0;
Andrew Trick328b2232011-03-14 16:48:10 +0000956
Matt Arsenault009faed2013-09-11 05:09:42 +0000957 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
958
Chris Lattner0f4a6402011-02-19 19:31:39 +0000959 // If we're allowed to form a memset, and the stored value would be acceptable
960 // for memset, use it.
961 if (SplatValue && TLI->has(LibFunc::memset) &&
962 // Verify that the stored value is loop invariant. If not, we can't
963 // promote the memset.
964 CurLoop->isLoopInvariant(SplatValue)) {
965 // Keep and use SplatValue.
966 PatternValue = 0;
Matt Arsenault009faed2013-09-11 05:09:42 +0000967 } else if (DestAS == 0 &&
968 TLI->has(LibFunc::memset_pattern16) &&
Chris Lattner0f4a6402011-02-19 19:31:39 +0000969 (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000970 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000971 // It looks like we can use PatternValue!
972 SplatValue = 0;
973 } else {
974 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000975 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000976 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000977 }
Andrew Trick328b2232011-03-14 16:48:10 +0000978
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000979 // The trip count of the loop and the base pointer of the addrec SCEV is
980 // guaranteed to be loop invariant, which means that it should dominate the
981 // header. This allows us to insert code for it in the preheader.
982 BasicBlock *Preheader = CurLoop->getLoopPreheader();
983 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick411daa52011-06-28 05:07:32 +0000984 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000985
Matt Arsenault009faed2013-09-11 05:09:42 +0000986 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
987
Chris Lattner29e14ed2010-12-26 23:42:51 +0000988 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000989 // this into a memset in the loop preheader now if we want. However, this
990 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000991 // or write to the aliased location. Check for any overlap by generating the
992 // base pointer and checking the region.
Andrew Trick328b2232011-03-14 16:48:10 +0000993 Value *BasePtr =
Matt Arsenault009faed2013-09-11 05:09:42 +0000994 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
Chris Lattner29e14ed2010-12-26 23:42:51 +0000995 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000996
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000997 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
998 CurLoop, BECount,
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000999 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001000 Expander.clear();
1001 // If we generated new code for the base pointer, clean up.
1002 deleteIfDeadInstruction(BasePtr, *SE, TLI);
1003 return false;
1004 }
1005
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001006 // Okay, everything looks good, insert the memset.
1007
Chris Lattner29e14ed2010-12-26 23:42:51 +00001008 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1009 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +00001010 Type *IntPtr = Builder.getIntPtrTy(TD, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +00001011 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +00001012
Chris Lattner29e14ed2010-12-26 23:42:51 +00001013 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +00001014 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001015 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +00001016 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001017 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001018 }
Andrew Trick328b2232011-03-14 16:48:10 +00001019
1020 Value *NumBytes =
Chris Lattner29e14ed2010-12-26 23:42:51 +00001021 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001022
Devang Pateld00c6282011-03-07 22:43:45 +00001023 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +00001024 if (SplatValue) {
1025 NewCall = Builder.CreateMemSet(BasePtr,
1026 SplatValue,
1027 NumBytes,
1028 StoreAlignment);
1029 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +00001030 // Everything is emitted in default address space
1031 Type *Int8PtrTy = DestInt8PtrTy;
1032
Chris Lattner0f4a6402011-02-19 19:31:39 +00001033 Module *M = TheStore->getParent()->getParent()->getParent();
1034 Value *MSP = M->getOrInsertFunction("memset_pattern16",
1035 Builder.getVoidTy(),
Matt Arsenault009faed2013-09-11 05:09:42 +00001036 Int8PtrTy,
1037 Int8PtrTy,
1038 IntPtr,
Chris Lattner0f4a6402011-02-19 19:31:39 +00001039 (void*)0);
Andrew Trick328b2232011-03-14 16:48:10 +00001040
Chris Lattner0f4a6402011-02-19 19:31:39 +00001041 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1042 // an constant array of 16-bytes. Plop the value into a mergable global.
1043 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1044 GlobalValue::InternalLinkage,
1045 PatternValue, ".memset_pattern");
1046 GV->setUnnamedAddr(true); // Ok to merge these.
1047 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +00001048 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
Chris Lattner0f4a6402011-02-19 19:31:39 +00001049 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1050 }
Andrew Trick328b2232011-03-14 16:48:10 +00001051
Chris Lattner29e14ed2010-12-26 23:42:51 +00001052 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +00001053 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +00001054 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001055
Chris Lattnerb9fe6852010-12-27 00:03:23 +00001056 // Okay, the memset has been formed. Zap the original store and anything that
1057 // feeds into it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001058 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +00001059 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +00001060 return true;
1061}
1062
Chris Lattner85b6d812011-01-02 03:37:56 +00001063/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1064/// same-strided load.
1065bool LoopIdiomRecognize::
1066processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1067 const SCEVAddRecExpr *StoreEv,
1068 const SCEVAddRecExpr *LoadEv,
1069 const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +00001070 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001071 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +00001072 return false;
Andrew Trick328b2232011-03-14 16:48:10 +00001073
Chris Lattner85b6d812011-01-02 03:37:56 +00001074 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +00001075
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001076 // The trip count of the loop and the base pointer of the addrec SCEV is
1077 // guaranteed to be loop invariant, which means that it should dominate the
1078 // header. This allows us to insert code for it in the preheader.
1079 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1080 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick411daa52011-06-28 05:07:32 +00001081 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001082
Chris Lattner85b6d812011-01-02 03:37:56 +00001083 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001084 // this into a memcpy in the loop preheader now if we want. However, this
1085 // would be unsafe to do if there is anything else in the loop that may read
1086 // or write the memory region we're storing to. This includes the load that
1087 // feeds the stores. Check for an alias by generating the base address and
1088 // checking everything.
Andrew Trick328b2232011-03-14 16:48:10 +00001089 Value *StoreBasePtr =
Chris Lattner85b6d812011-01-02 03:37:56 +00001090 Expander.expandCodeFor(StoreEv->getStart(),
1091 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1092 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001093
1094 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1095 CurLoop, BECount, StoreSize,
1096 getAnalysis<AliasAnalysis>(), SI)) {
1097 Expander.clear();
1098 // If we generated new code for the base pointer, clean up.
1099 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1100 return false;
1101 }
1102
1103 // For a memcpy, we have to make sure that the input array is not being
1104 // mutated by the loop.
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001105 Value *LoadBasePtr =
1106 Expander.expandCodeFor(LoadEv->getStart(),
1107 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1108 Preheader->getTerminator());
1109
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001110 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1111 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1112 Expander.clear();
1113 // If we generated new code for the base pointer, clean up.
1114 deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1115 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1116 return false;
1117 }
1118
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001119 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001120
Andrew Trick328b2232011-03-14 16:48:10 +00001121
Chris Lattner85b6d812011-01-02 03:37:56 +00001122 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1123 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +00001124 Type *IntPtrTy = Builder.getIntPtrTy(TD, SI->getPointerAddressSpace());
1125 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +00001126
Matt Arsenault009faed2013-09-11 05:09:42 +00001127 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +00001128 SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +00001129 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +00001130 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001131 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +00001132
Chris Lattner85b6d812011-01-02 03:37:56 +00001133 Value *NumBytes =
Matt Arsenault009faed2013-09-11 05:09:42 +00001134 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001135
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001136 CallInst *NewCall =
1137 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1138 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +00001139 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001140
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001141 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001142 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1143 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001144
Andrew Trick328b2232011-03-14 16:48:10 +00001145
Chris Lattner85b6d812011-01-02 03:37:56 +00001146 // Okay, the memset has been formed. Zap the original store and anything that
1147 // feeds into it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001148 deleteDeadInstruction(SI, *SE, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001149 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001150 return true;
1151}