blob: 26a83dfdc3c0ced8d163465425f20486999878a4 [file] [log] [blame]
Chris Lattnere6bb6492010-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 Lattnerbdce5722011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
Chandler Carrutha8647482012-11-02 08:33:25 +000019// memcmp, memmove, strlen, etc.
Chris Lattnerbdce5722011-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 Lattner91139cc2011-01-02 23:19:45 +000033//
Chris Lattner408b5342011-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 Lattnerd957c712011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner91139cc2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattnerbdce5722011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000043
Chris Lattnere6bb6492010-12-26 19:39:38 +000044#include "llvm/Transforms/Scalar.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000045#include "llvm/ADT/Statistic.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000046#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000047#include "llvm/Analysis/LoopPass.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000049#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthbe049292013-01-07 03:08:10 +000050#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner22920b52010-12-26 20:45:45 +000051#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000052#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070053#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000054#include "llvm/IR/IRBuilder.h"
55#include "llvm/IR/IntrinsicInst.h"
56#include "llvm/IR/Module.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000057#include "llvm/Support/Debug.h"
58#include "llvm/Support/raw_ostream.h"
Chris Lattnerc19175c2011-02-18 22:22:15 +000059#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner9f391882010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000061using namespace llvm;
62
Stephen Hinesdce4a402014-05-29 02:49:00 -070063#define DEBUG_TYPE "loop-idiom"
64
Chandler Carrutha8647482012-11-02 08:33:25 +000065STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000067
68namespace {
Shuxin Yang5518a132012-12-09 03:12:46 +000069
70 class LoopIdiomRecognize;
71
72 /// This class defines some utility functions for loop idiom recognization.
73 class LIRUtil {
74 public:
75 /// Return true iff the block contains nothing but an uncondition branch
76 /// (aka goto instruction).
77 static bool isAlmostEmpty(BasicBlock *);
78
79 static BranchInst *getBranch(BasicBlock *BB) {
80 return dyn_cast<BranchInst>(BB->getTerminator());
81 }
82
Matt Arsenault1f4492e2013-07-22 18:59:58 +000083 /// Derive the precondition block (i.e the block that guards the loop
Shuxin Yang5518a132012-12-09 03:12:46 +000084 /// preheader) from the given preheader.
85 static BasicBlock *getPrecondBb(BasicBlock *PreHead);
86 };
87
88 /// This class is to recoginize idioms of population-count conducted in
89 /// a noncountable loop. Currently it only recognizes this pattern:
90 /// \code
91 /// while(x) {cnt++; ...; x &= x - 1; ...}
92 /// \endcode
93 class NclPopcountRecognize {
94 LoopIdiomRecognize &LIR;
95 Loop *CurLoop;
96 BasicBlock *PreCondBB;
97
98 typedef IRBuilder<> IRBuilderTy;
99
100 public:
101 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
102 bool recognize();
103
104 private:
105 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
106 /// the idiom.
107 bool preliminaryScreen();
108
109 /// Check if the given conditional branch is based on the comparison
Stephen Hines36b56882014-04-23 16:57:46 -0700110 /// between a variable and zero, and if the variable is non-zero, the
111 /// control yields to the loop entry. If the branch matches the behavior,
Shuxin Yang5518a132012-12-09 03:12:46 +0000112 /// the variable involved in the comparion is returned. This function will
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000113 /// be called to see if the precondition and postcondition of the loop
Shuxin Yang5518a132012-12-09 03:12:46 +0000114 /// are in desirable form.
115 Value *matchCondition (BranchInst *Br, BasicBlock *NonZeroTarget) const;
116
117 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
Stephen Hinesdce4a402014-05-29 02:49:00 -0700118 /// is set to the instruction counting the population bit. 2) \p CntPhi
Shuxin Yang5518a132012-12-09 03:12:46 +0000119 /// is set to the corresponding phi node. 3) \p Var is set to the value
120 /// whose population bits are being counted.
121 bool detectIdiom
122 (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
123
124 /// Insert ctpop intrinsic function and some obviously dead instructions.
125 void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var);
126
127 /// Create llvm.ctpop.* intrinsic function.
128 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
129 };
130
Chris Lattnere6bb6492010-12-26 19:39:38 +0000131 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +0000132 Loop *CurLoop;
Stephen Hines36b56882014-04-23 16:57:46 -0700133 const DataLayout *DL;
Chris Lattner62c50fd2011-01-02 19:01:03 +0000134 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +0000135 ScalarEvolution *SE;
Chris Lattnerc19175c2011-02-18 22:22:15 +0000136 TargetLibraryInfo *TLI;
Chandler Carruth9980b8a2013-01-05 10:00:09 +0000137 const TargetTransformInfo *TTI;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000138 public:
139 static char ID;
140 explicit LoopIdiomRecognize() : LoopPass(ID) {
141 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700142 DL = nullptr; DT = nullptr; SE = nullptr; TLI = nullptr; TTI = nullptr;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000143 }
144
Stephen Hines36b56882014-04-23 16:57:46 -0700145 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner62c50fd2011-01-02 19:01:03 +0000146 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
147 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +0000148
Chris Lattner22920b52010-12-26 20:45:45 +0000149 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000150 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000151
Chris Lattner3a393722011-02-19 19:31:39 +0000152 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
153 unsigned StoreAlignment,
154 Value *SplatValue, Instruction *TheStore,
155 const SCEVAddRecExpr *Ev,
156 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +0000157 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
158 const SCEVAddRecExpr *StoreEv,
159 const SCEVAddRecExpr *LoadEv,
160 const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000161
Chris Lattnere6bb6492010-12-26 19:39:38 +0000162 /// This transformation requires natural loop information & requires that
163 /// loop preheaders be inserted into the CFG.
164 ///
Stephen Hines36b56882014-04-23 16:57:46 -0700165 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattnere6bb6492010-12-26 19:39:38 +0000166 AU.addRequired<LoopInfo>();
167 AU.addPreserved<LoopInfo>();
168 AU.addRequiredID(LoopSimplifyID);
169 AU.addPreservedID(LoopSimplifyID);
170 AU.addRequiredID(LCSSAID);
171 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000172 AU.addRequired<AliasAnalysis>();
173 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000174 AU.addRequired<ScalarEvolution>();
175 AU.addPreserved<ScalarEvolution>();
Stephen Hines36b56882014-04-23 16:57:46 -0700176 AU.addPreserved<DominatorTreeWrapperPass>();
177 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000178 AU.addRequired<TargetLibraryInfo>();
Chandler Carruthd12aae62013-01-07 09:17:41 +0000179 AU.addRequired<TargetTransformInfo>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000180 }
Shuxin Yang5518a132012-12-09 03:12:46 +0000181
182 const DataLayout *getDataLayout() {
Stephen Hines36b56882014-04-23 16:57:46 -0700183 if (DL)
184 return DL;
185 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700186 DL = DLP ? &DLP->getDataLayout() : nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700187 return DL;
Shuxin Yang5518a132012-12-09 03:12:46 +0000188 }
189
190 DominatorTree *getDominatorTree() {
Stephen Hines36b56882014-04-23 16:57:46 -0700191 return DT ? DT
192 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Shuxin Yang5518a132012-12-09 03:12:46 +0000193 }
194
195 ScalarEvolution *getScalarEvolution() {
196 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
197 }
198
199 TargetLibraryInfo *getTargetLibraryInfo() {
200 return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
201 }
202
Chandler Carruth9980b8a2013-01-05 10:00:09 +0000203 const TargetTransformInfo *getTargetTransformInfo() {
Chandler Carruthd12aae62013-01-07 09:17:41 +0000204 return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
Shuxin Yang5518a132012-12-09 03:12:46 +0000205 }
206
207 Loop *getLoop() const { return CurLoop; }
208
209 private:
210 bool runOnNoncountableLoop();
211 bool runOnCountableLoop();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000212 };
213}
214
215char LoopIdiomRecognize::ID = 0;
216INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
217 false, false)
218INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Stephen Hines36b56882014-04-23 16:57:46 -0700219INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000220INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
221INITIALIZE_PASS_DEPENDENCY(LCSSA)
222INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnerc19175c2011-02-18 22:22:15 +0000223INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000224INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruthd12aae62013-01-07 09:17:41 +0000225INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000226INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
227 false, false)
228
229Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
230
Chris Lattner4f81b542011-05-22 17:39:56 +0000231/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattner9f391882010-12-27 00:03:23 +0000232/// and zero out all the operands of this instruction. If any of them become
233/// dead, delete them and the computation tree that feeds them.
234///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000235static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
236 const TargetLibraryInfo *TLI) {
Chris Lattner9f391882010-12-27 00:03:23 +0000237 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000238
Chris Lattner9f391882010-12-27 00:03:23 +0000239 NowDeadInsts.push_back(I);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000240
Chris Lattner9f391882010-12-27 00:03:23 +0000241 // Before we touch this instruction, remove it from SE!
242 do {
243 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000244
Chris Lattner9f391882010-12-27 00:03:23 +0000245 // This instruction is dead, zap it, in stages. Start by removing it from
246 // SCEV.
247 SE.forgetValue(DeadInst);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000248
Chris Lattner9f391882010-12-27 00:03:23 +0000249 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
250 Value *Op = DeadInst->getOperand(op);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700251 DeadInst->setOperand(op, nullptr);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000252
Chris Lattner9f391882010-12-27 00:03:23 +0000253 // If this operand just became dead, add it to the NowDeadInsts list.
254 if (!Op->use_empty()) continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000255
Chris Lattner9f391882010-12-27 00:03:23 +0000256 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000257 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattner9f391882010-12-27 00:03:23 +0000258 NowDeadInsts.push_back(OpI);
259 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000260
Chris Lattner9f391882010-12-27 00:03:23 +0000261 DeadInst->eraseFromParent();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000262
Chris Lattner9f391882010-12-27 00:03:23 +0000263 } while (!NowDeadInsts.empty());
264}
265
Chandler Carrutha8647482012-11-02 08:33:25 +0000266/// deleteIfDeadInstruction - If the specified value is a dead instruction,
267/// delete it and any recursively used instructions.
268static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
269 const TargetLibraryInfo *TLI) {
270 if (Instruction *I = dyn_cast<Instruction>(V))
271 if (isInstructionTriviallyDead(I, TLI))
272 deleteDeadInstruction(I, SE, TLI);
273}
274
Shuxin Yang5518a132012-12-09 03:12:46 +0000275//===----------------------------------------------------------------------===//
276//
277// Implementation of LIRUtil
278//
279//===----------------------------------------------------------------------===//
280
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000281// This function will return true iff the given block contains nothing but goto.
282// A typical usage of this function is to check if the preheader function is
283// "almost" empty such that generated intrinsic functions can be moved across
284// the preheader and be placed at the end of the precondition block without
285// the concern of breaking data dependence.
Shuxin Yang5518a132012-12-09 03:12:46 +0000286bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
287 if (BranchInst *Br = getBranch(BB)) {
288 return Br->isUnconditional() && BB->size() == 1;
289 }
290 return false;
291}
292
Shuxin Yang5518a132012-12-09 03:12:46 +0000293BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
294 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
295 BranchInst *Br = getBranch(BB);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700296 return Br && Br->isConditional() ? BB : nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000297 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700298 return nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000299}
300
301//===----------------------------------------------------------------------===//
302//
303// Implementation of NclPopcountRecognize
304//
305//===----------------------------------------------------------------------===//
306
307NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
Stephen Hinesdce4a402014-05-29 02:49:00 -0700308 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
Shuxin Yang5518a132012-12-09 03:12:46 +0000309}
310
311bool NclPopcountRecognize::preliminaryScreen() {
Chandler Carruth9980b8a2013-01-05 10:00:09 +0000312 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
Chandler Carruthd1b8ef92013-01-07 03:16:03 +0000313 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
Shuxin Yang5518a132012-12-09 03:12:46 +0000314 return false;
315
Robert Wilhelm3f4f4202013-09-28 13:42:22 +0000316 // Counting population are usually conducted by few arithmetic instructions.
Shuxin Yang5518a132012-12-09 03:12:46 +0000317 // Such instructions can be easilly "absorbed" by vacant slots in a
318 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
319 // in a compact loop.
320
321 // Give up if the loop has multiple blocks or multiple backedges.
322 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
323 return false;
324
325 BasicBlock *LoopBody = *(CurLoop->block_begin());
326 if (LoopBody->size() >= 20) {
327 // The loop is too big, bail out.
328 return false;
329 }
330
331 // It should have a preheader containing nothing but a goto instruction.
332 BasicBlock *PreHead = CurLoop->getLoopPreheader();
333 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
334 return false;
335
336 // It should have a precondition block where the generated popcount instrinsic
337 // function will be inserted.
338 PreCondBB = LIRUtil::getPrecondBb(PreHead);
339 if (!PreCondBB)
340 return false;
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000341
Shuxin Yang5518a132012-12-09 03:12:46 +0000342 return true;
343}
344
Stephen Hinesdce4a402014-05-29 02:49:00 -0700345Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
346 BasicBlock *LoopEntry) const {
Shuxin Yang5518a132012-12-09 03:12:46 +0000347 if (!Br || !Br->isConditional())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700348 return nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000349
350 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
351 if (!Cond)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700352 return nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000353
354 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
355 if (!CmpZero || !CmpZero->isZero())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700356 return nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000357
358 ICmpInst::Predicate Pred = Cond->getPredicate();
359 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
360 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
361 return Cond->getOperand(0);
362
Stephen Hinesdce4a402014-05-29 02:49:00 -0700363 return nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000364}
365
366bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
367 PHINode *&CntPhi,
368 Value *&Var) const {
369 // Following code tries to detect this idiom:
370 //
371 // if (x0 != 0)
372 // goto loop-exit // the precondition of the loop
373 // cnt0 = init-val;
374 // do {
375 // x1 = phi (x0, x2);
376 // cnt1 = phi(cnt0, cnt2);
377 //
378 // cnt2 = cnt1 + 1;
379 // ...
380 // x2 = x1 & (x1 - 1);
381 // ...
382 // } while(x != 0);
383 //
384 // loop-exit:
385 //
386
387 // step 1: Check to see if the look-back branch match this pattern:
388 // "if (a!=0) goto loop-entry".
389 BasicBlock *LoopEntry;
390 Instruction *DefX2, *CountInst;
391 Value *VarX1, *VarX0;
392 PHINode *PhiX, *CountPhi;
393
Stephen Hinesdce4a402014-05-29 02:49:00 -0700394 DefX2 = CountInst = nullptr;
395 VarX1 = VarX0 = nullptr;
396 PhiX = CountPhi = nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000397 LoopEntry = *(CurLoop->block_begin());
398
399 // step 1: Check if the loop-back branch is in desirable form.
400 {
401 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
402 DefX2 = dyn_cast<Instruction>(T);
403 else
404 return false;
405 }
406
407 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
408 {
Shuxin Yang253449d2013-01-10 23:32:01 +0000409 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
Shuxin Yang5518a132012-12-09 03:12:46 +0000410 return false;
411
412 BinaryOperator *SubOneOp;
413
414 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
415 VarX1 = DefX2->getOperand(1);
416 else {
417 VarX1 = DefX2->getOperand(0);
418 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
419 }
420 if (!SubOneOp)
421 return false;
422
423 Instruction *SubInst = cast<Instruction>(SubOneOp);
424 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
425 if (!Dec ||
426 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
427 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
428 return false;
429 }
430 }
431
432 // step 3: Check the recurrence of variable X
433 {
434 PhiX = dyn_cast<PHINode>(VarX1);
435 if (!PhiX ||
436 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
437 return false;
438 }
439 }
440
441 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
442 {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700443 CountInst = nullptr;
Shuxin Yang5518a132012-12-09 03:12:46 +0000444 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
445 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
446 Instruction *Inst = Iter;
447 if (Inst->getOpcode() != Instruction::Add)
448 continue;
449
450 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
451 if (!Inc || !Inc->isOne())
452 continue;
453
454 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
455 if (!Phi || Phi->getParent() != LoopEntry)
456 continue;
457
458 // Check if the result of the instruction is live of the loop.
459 bool LiveOutLoop = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700460 for (User *U : Inst->users()) {
461 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
Shuxin Yang5518a132012-12-09 03:12:46 +0000462 LiveOutLoop = true; break;
463 }
464 }
465
466 if (LiveOutLoop) {
467 CountInst = Inst;
468 CountPhi = Phi;
469 break;
470 }
471 }
472
473 if (!CountInst)
474 return false;
475 }
476
477 // step 5: check if the precondition is in this form:
478 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
479 {
480 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
481 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
482 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
483 return false;
484
485 CntInst = CountInst;
486 CntPhi = CountPhi;
487 Var = T;
488 }
489
490 return true;
491}
492
493void NclPopcountRecognize::transform(Instruction *CntInst,
494 PHINode *CntPhi, Value *Var) {
495
496 ScalarEvolution *SE = LIR.getScalarEvolution();
497 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
498 BasicBlock *PreHead = CurLoop->getLoopPreheader();
499 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
500 const DebugLoc DL = CntInst->getDebugLoc();
501
502 // Assuming before transformation, the loop is following:
503 // if (x) // the precondition
504 // do { cnt++; x &= x - 1; } while(x);
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000505
Shuxin Yang5518a132012-12-09 03:12:46 +0000506 // Step 1: Insert the ctpop instruction at the end of the precondition block
507 IRBuilderTy Builder(PreCondBr);
508 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
509 {
510 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
511 NewCount = PopCntZext =
512 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
513
514 if (NewCount != PopCnt)
515 (cast<Instruction>(NewCount))->setDebugLoc(DL);
516
517 // TripCnt is exactly the number of iterations the loop has
518 TripCnt = NewCount;
519
Stephen Hines36b56882014-04-23 16:57:46 -0700520 // If the population counter's initial value is not zero, insert Add Inst.
Shuxin Yang5518a132012-12-09 03:12:46 +0000521 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
522 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
523 if (!InitConst || !InitConst->isZero()) {
524 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
525 (cast<Instruction>(NewCount))->setDebugLoc(DL);
526 }
527 }
528
529 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
530 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
531 // function would be partial dead code, and downstream passes will drag
532 // it back from the precondition block to the preheader.
533 {
534 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
535
536 Value *Opnd0 = PopCntZext;
537 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
538 if (PreCond->getOperand(0) != Var)
539 std::swap(Opnd0, Opnd1);
540
541 ICmpInst *NewPreCond =
542 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
543 PreCond->replaceAllUsesWith(NewPreCond);
544
545 deleteDeadInstruction(PreCond, *SE, TLI);
546 }
547
548 // Step 3: Note that the population count is exactly the trip count of the
549 // loop in question, which enble us to to convert the loop from noncountable
550 // loop into a countable one. The benefit is twofold:
551 //
552 // - If the loop only counts population, the entire loop become dead after
553 // the transformation. It is lots easier to prove a countable loop dead
554 // than to prove a noncountable one. (In some C dialects, a infite loop
555 // isn't dead even if it computes nothing useful. In general, DCE needs
556 // to prove a noncountable loop finite before safely delete it.)
557 //
558 // - If the loop also performs something else, it remains alive.
559 // Since it is transformed to countable form, it can be aggressively
560 // optimized by some optimizations which are in general not applicable
561 // to a noncountable loop.
562 //
563 // After this step, this loop (conceptually) would look like following:
564 // newcnt = __builtin_ctpop(x);
565 // t = newcnt;
566 // if (x)
567 // do { cnt++; x &= x-1; t--) } while (t > 0);
568 BasicBlock *Body = *(CurLoop->block_begin());
569 {
570 BranchInst *LbBr = LIRUtil::getBranch(Body);
571 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
572 Type *Ty = TripCnt->getType();
573
574 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
575
576 Builder.SetInsertPoint(LbCond);
577 Value *Opnd1 = cast<Value>(TcPhi);
578 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
579 Instruction *TcDec =
580 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
581
582 TcPhi->addIncoming(TripCnt, PreHead);
583 TcPhi->addIncoming(TcDec, Body);
584
585 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
586 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
587 LbCond->setPredicate(Pred);
588 LbCond->setOperand(0, TcDec);
589 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
590 }
591
592 // Step 4: All the references to the original population counter outside
593 // the loop are replaced with the NewCount -- the value returned from
594 // __builtin_ctpop().
595 {
596 SmallVector<Value *, 4> CntUses;
Stephen Hines36b56882014-04-23 16:57:46 -0700597 for (User *U : CntInst->users())
598 if (cast<Instruction>(U)->getParent() != Body)
599 CntUses.push_back(U);
Shuxin Yang5518a132012-12-09 03:12:46 +0000600 for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
601 (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
602 }
603 }
604
605 // step 5: Forget the "non-computable" trip-count SCEV associated with the
606 // loop. The loop would otherwise not be deleted even if it becomes empty.
607 SE->forgetLoop(CurLoop);
608}
609
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000610CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
Shuxin Yang5518a132012-12-09 03:12:46 +0000611 Value *Val, DebugLoc DL) {
612 Value *Ops[] = { Val };
613 Type *Tys[] = { Val->getType() };
614
615 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
616 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
617 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
618 CI->setDebugLoc(DL);
619
620 return CI;
621}
622
623/// recognize - detect population count idiom in a non-countable loop. If
624/// detected, transform the relevant code to popcount intrinsic function
625/// call, and return true; otherwise, return false.
626bool NclPopcountRecognize::recognize() {
627
Chandler Carruth9980b8a2013-01-05 10:00:09 +0000628 if (!LIR.getTargetTransformInfo())
Shuxin Yang5518a132012-12-09 03:12:46 +0000629 return false;
630
631 LIR.getScalarEvolution();
632
633 if (!preliminaryScreen())
634 return false;
635
636 Instruction *CntInst;
637 PHINode *CntPhi;
638 Value *Val;
639 if (!detectIdiom(CntInst, CntPhi, Val))
640 return false;
641
642 transform(CntInst, CntPhi, Val);
643 return true;
644}
645
646//===----------------------------------------------------------------------===//
647//
648// Implementation of LoopIdiomRecognize
649//
650//===----------------------------------------------------------------------===//
651
652bool LoopIdiomRecognize::runOnCountableLoop() {
653 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
654 if (isa<SCEVCouldNotCompute>(BECount)) return false;
655
656 // If this loop executes exactly one time, then it should be peeled, not
657 // optimized by this pass.
658 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
659 if (BECst->getValue()->getValue() == 0)
660 return false;
661
662 // We require target data for now.
663 if (!getDataLayout())
664 return false;
665
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000666 // set DT
Shuxin Yangcbf53732013-01-02 18:26:31 +0000667 (void)getDominatorTree();
Shuxin Yang5518a132012-12-09 03:12:46 +0000668
669 LoopInfo &LI = getAnalysis<LoopInfo>();
670 TLI = &getAnalysis<TargetLibraryInfo>();
671
Matt Arsenault1f4492e2013-07-22 18:59:58 +0000672 // set TLI
Shuxin Yangcbf53732013-01-02 18:26:31 +0000673 (void)getTargetLibraryInfo();
Shuxin Yang5518a132012-12-09 03:12:46 +0000674
675 SmallVector<BasicBlock*, 8> ExitBlocks;
676 CurLoop->getUniqueExitBlocks(ExitBlocks);
677
678 DEBUG(dbgs() << "loop-idiom Scanning: F["
679 << CurLoop->getHeader()->getParent()->getName()
680 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
681
682 bool MadeChange = false;
683 // Scan all the blocks in the loop that are not in subloops.
684 for (Loop::block_iterator BI = CurLoop->block_begin(),
685 E = CurLoop->block_end(); BI != E; ++BI) {
686 // Ignore blocks in subloops.
687 if (LI.getLoopFor(*BI) != CurLoop)
688 continue;
689
690 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
691 }
692 return MadeChange;
693}
694
695bool LoopIdiomRecognize::runOnNoncountableLoop() {
696 NclPopcountRecognize Popcount(*this);
697 if (Popcount.recognize())
698 return true;
699
700 return false;
701}
702
Chris Lattnere6bb6492010-12-26 19:39:38 +0000703bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Stephen Hines36b56882014-04-23 16:57:46 -0700704 if (skipOptnoneFunction(L))
705 return false;
706
Chris Lattner22920b52010-12-26 20:45:45 +0000707 CurLoop = L;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000708
Benjamin Kramer28aff842012-09-21 17:27:23 +0000709 // If the loop could not be converted to canonical form, it must have an
710 // indirectbr in it, just give up.
711 if (!L->getLoopPreheader())
712 return false;
713
Nadav Rotema94d6e82012-07-24 10:51:42 +0000714 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosier71400b62011-07-15 18:25:04 +0000715 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carrutha8647482012-11-02 08:33:25 +0000716 if (Name == "memset" || Name == "memcpy")
Chad Rosier71400b62011-07-15 18:25:04 +0000717 return false;
718
Chris Lattner22920b52010-12-26 20:45:45 +0000719 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang5518a132012-12-09 03:12:46 +0000720 if (SE->hasLoopInvariantBackedgeTakenCount(L))
721 return runOnCountableLoop();
722 return runOnNoncountableLoop();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000723}
724
725/// runOnLoopBlock - Process the specified block, which lives in a counted loop
726/// with the specified backedge count. This block is known to be in the current
727/// loop and not in any subloops.
728bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
729 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
730 // We can only promote stores in this block if they are unconditionally
731 // executed in the loop. For a block to be unconditionally executed, it has
732 // to dominate all the exit blocks of the loop. Verify this now.
733 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
734 if (!DT->dominates(BB, ExitBlocks[i]))
735 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000736
Chris Lattner22920b52010-12-26 20:45:45 +0000737 bool MadeChange = false;
738 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000739 Instruction *Inst = I++;
740 // Look for store instructions, which may be optimized to memset/memcpy.
741 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000742 WeakVH InstPtr(I);
743 if (!processLoopStore(SI, BECount)) continue;
744 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000745
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000746 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000747 // top of the block.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700748 if (!InstPtr)
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000749 I = BB->begin();
750 continue;
751 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000752
Chris Lattnere41d3c02011-01-04 07:46:33 +0000753 // Look for memset instructions, which may be optimized to a larger memset.
754 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
755 WeakVH InstPtr(I);
756 if (!processLoopMemSet(MSI, BECount)) continue;
757 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000758
Chris Lattnere41d3c02011-01-04 07:46:33 +0000759 // If processing the memset invalidated our iterator, start over from the
760 // top of the block.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700761 if (!InstPtr)
Chris Lattnere41d3c02011-01-04 07:46:33 +0000762 I = BB->begin();
763 continue;
764 }
Chris Lattner22920b52010-12-26 20:45:45 +0000765 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000766
Chris Lattner22920b52010-12-26 20:45:45 +0000767 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000768}
769
Chris Lattner62c50fd2011-01-02 19:01:03 +0000770
Chris Lattnere41d3c02011-01-04 07:46:33 +0000771/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000772bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman2bc3d522011-09-12 20:23:13 +0000773 if (!SI->isSimple()) return false;
Chris Lattnere41d3c02011-01-04 07:46:33 +0000774
Chris Lattner22920b52010-12-26 20:45:45 +0000775 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000776 Value *StorePtr = SI->getPointerOperand();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000777
Chris Lattner95ae6762010-12-28 18:53:48 +0000778 // Reject stores that are so large that they overflow an unsigned.
Stephen Hines36b56882014-04-23 16:57:46 -0700779 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000780 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000781 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000782
Chris Lattner22920b52010-12-26 20:45:45 +0000783 // See if the pointer expression is an AddRec like {base,+,1} on the current
784 // loop, which indicates a strided store. If we have something else, it's a
785 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000786 const SCEVAddRecExpr *StoreEv =
787 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700788 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000789 return false;
790
791 // Check to see if the stride matches the size of the store. If so, then we
792 // know that every byte is touched in the loop.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000793 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000794 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000795
Stephen Hinesdce4a402014-05-29 02:49:00 -0700796 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
Chris Lattner408b5342011-02-21 02:08:54 +0000797 // TODO: Could also handle negative stride here someday, that will require
798 // the validity check in mayLoopAccessLocation to be updated though.
799 // Enable this to print exact negative strides.
Chris Lattner0e68cee2011-02-21 17:02:55 +0000800 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattner408b5342011-02-21 02:08:54 +0000801 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
802 dbgs() << "BB: " << *SI->getParent();
803 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000804
Chris Lattner22920b52010-12-26 20:45:45 +0000805 return false;
Chris Lattner408b5342011-02-21 02:08:54 +0000806 }
Chris Lattner3a393722011-02-19 19:31:39 +0000807
808 // See if we can optimize just this store in isolation.
809 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
810 StoredVal, SI, StoreEv, BECount))
811 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000812
Chris Lattnere2c43922011-01-02 03:37:56 +0000813 // If the stored value is a strided load in the same loop with the same stride
814 // this this may be transformable into a memcpy. This kicks in for stuff like
815 // for (i) A[i] = B[i];
816 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
817 const SCEVAddRecExpr *LoadEv =
818 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
819 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman2bc3d522011-09-12 20:23:13 +0000820 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattnere2c43922011-01-02 03:37:56 +0000821 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
822 return true;
823 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000824 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000825
Chris Lattnere6bb6492010-12-26 19:39:38 +0000826 return false;
827}
828
Chris Lattnere41d3c02011-01-04 07:46:33 +0000829/// processLoopMemSet - See if this memset can be promoted to a large memset.
830bool LoopIdiomRecognize::
831processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
832 // We can only handle non-volatile memsets with a constant size.
833 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
834
Chris Lattnerc19175c2011-02-18 22:22:15 +0000835 // If we're not allowed to hack on memset, we fail.
836 if (!TLI->has(LibFunc::memset))
837 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000838
Chris Lattnere41d3c02011-01-04 07:46:33 +0000839 Value *Pointer = MSI->getDest();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000840
Chris Lattnere41d3c02011-01-04 07:46:33 +0000841 // See if the pointer expression is an AddRec like {base,+,1} on the current
842 // loop, which indicates a strided store. If we have something else, it's a
843 // random store we can't handle.
844 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700845 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattnere41d3c02011-01-04 07:46:33 +0000846 return false;
847
848 // Reject memsets that are so large that they overflow an unsigned.
849 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
850 if ((SizeInBytes >> 32) != 0)
851 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000852
Chris Lattnere41d3c02011-01-04 07:46:33 +0000853 // Check to see if the stride matches the size of the memset. If so, then we
854 // know that every byte is touched in the loop.
855 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000856
Chris Lattnere41d3c02011-01-04 07:46:33 +0000857 // TODO: Could also handle negative stride here someday, that will require the
858 // validity check in mayLoopAccessLocation to be updated though.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700859 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattnere41d3c02011-01-04 07:46:33 +0000860 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000861
Chris Lattner3a393722011-02-19 19:31:39 +0000862 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
863 MSI->getAlignment(), MSI->getValue(),
864 MSI, Ev, BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000865}
866
Chandler Carrutha8647482012-11-02 08:33:25 +0000867
868/// mayLoopAccessLocation - Return true if the specified loop might access the
869/// specified pointer location, which is a loop-strided access. The 'Access'
870/// argument specifies what the verboten forms of access are (read or write).
871static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
872 Loop *L, const SCEV *BECount,
873 unsigned StoreSize, AliasAnalysis &AA,
874 Instruction *IgnoredStore) {
875 // Get the location that may be stored across the loop. Since the access is
876 // strided positively through memory, we say that the modified location starts
877 // at the pointer and has infinite size.
878 uint64_t AccessSize = AliasAnalysis::UnknownSize;
879
880 // If the loop iterates a fixed number of times, we can refine the access size
881 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
882 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
883 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
884
885 // TODO: For this to be really effective, we have to dive into the pointer
886 // operand in the store. Store to &A[i] of 100 will always return may alias
887 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
888 // which will then no-alias a store to &A[100].
889 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
890
891 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
892 ++BI)
893 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
894 if (&*I != IgnoredStore &&
895 (AA.getModRefInfo(I, StoreLoc) & Access))
896 return true;
897
898 return false;
899}
900
Chris Lattner3a393722011-02-19 19:31:39 +0000901/// getMemSetPatternValue - If a strided store of the specified value is safe to
902/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
903/// be passed in. Otherwise, return null.
904///
905/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
906/// just replicate their input array and then pass on to memset_pattern16.
Stephen Hines36b56882014-04-23 16:57:46 -0700907static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner3a393722011-02-19 19:31:39 +0000908 // If the value isn't a constant, we can't promote it to being in a constant
909 // array. We could theoretically do a store to an alloca or something, but
910 // that doesn't seem worthwhile.
911 Constant *C = dyn_cast<Constant>(V);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700912 if (!C) return nullptr;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000913
Chris Lattner3a393722011-02-19 19:31:39 +0000914 // Only handle simple values that are a power of two bytes in size.
Stephen Hines36b56882014-04-23 16:57:46 -0700915 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chris Lattner3a393722011-02-19 19:31:39 +0000916 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700917 return nullptr;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000918
Chris Lattner80e8b502011-02-19 19:56:44 +0000919 // Don't care enough about darwin/ppc to implement this.
Stephen Hines36b56882014-04-23 16:57:46 -0700920 if (DL.isBigEndian())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700921 return nullptr;
Chris Lattner3a393722011-02-19 19:31:39 +0000922
923 // Convert to size in bytes.
924 Size /= 8;
Chris Lattner3a393722011-02-19 19:31:39 +0000925
Chris Lattner3a393722011-02-19 19:31:39 +0000926 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner80e8b502011-02-19 19:56:44 +0000927 // if the top and bottom are the same (e.g. for vectors and large integers).
Stephen Hinesdce4a402014-05-29 02:49:00 -0700928 if (Size > 16) return nullptr;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000929
Chris Lattner80e8b502011-02-19 19:56:44 +0000930 // If the constant is exactly 16 bytes, just use it.
931 if (Size == 16) return C;
Chris Lattner3a393722011-02-19 19:31:39 +0000932
Chris Lattner80e8b502011-02-19 19:56:44 +0000933 // Otherwise, we'll use an array of the constants.
934 unsigned ArraySize = 16/Size;
935 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
936 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner3a393722011-02-19 19:31:39 +0000937}
938
939
940/// processLoopStridedStore - We see a strided store of some value. If we can
941/// transform this into a memset or memset_pattern in the loop preheader, do so.
942bool LoopIdiomRecognize::
943processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
944 unsigned StoreAlignment, Value *StoredVal,
945 Instruction *TheStore, const SCEVAddRecExpr *Ev,
946 const SCEV *BECount) {
Andrew Trickd99b39e2011-03-14 16:48:10 +0000947
Chris Lattner3a393722011-02-19 19:31:39 +0000948 // If the stored value is a byte-wise value (like i32 -1), then it may be
949 // turned into a memset of i8 -1, assuming that all the consecutive bytes
950 // are stored. A store of i32 0x01020304 can never be turned into a memset,
951 // but it can be turned into memset_pattern if the target supports it.
952 Value *SplatValue = isBytewiseValue(StoredVal);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700953 Constant *PatternValue = nullptr;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000954
Matt Arsenault11250c12013-09-11 05:09:42 +0000955 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
956
Chris Lattner3a393722011-02-19 19:31:39 +0000957 // If we're allowed to form a memset, and the stored value would be acceptable
958 // for memset, use it.
959 if (SplatValue && TLI->has(LibFunc::memset) &&
960 // Verify that the stored value is loop invariant. If not, we can't
961 // promote the memset.
962 CurLoop->isLoopInvariant(SplatValue)) {
963 // Keep and use SplatValue.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700964 PatternValue = nullptr;
Matt Arsenault11250c12013-09-11 05:09:42 +0000965 } else if (DestAS == 0 &&
966 TLI->has(LibFunc::memset_pattern16) &&
Stephen Hines36b56882014-04-23 16:57:46 -0700967 (PatternValue = getMemSetPatternValue(StoredVal, *DL))) {
Matt Arsenault11250c12013-09-11 05:09:42 +0000968 // Don't create memset_pattern16s with address spaces.
Chris Lattner3a393722011-02-19 19:31:39 +0000969 // It looks like we can use PatternValue!
Stephen Hinesdce4a402014-05-29 02:49:00 -0700970 SplatValue = nullptr;
Chris Lattner3a393722011-02-19 19:31:39 +0000971 } else {
972 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedman5ac7c7d2011-09-13 00:44:16 +0000973 // do anything with a 3-byte store.
Chris Lattnerbafa1172011-01-01 20:12:04 +0000974 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000975 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000976
Chris Lattner4f81b542011-05-22 17:39:56 +0000977 // The trip count of the loop and the base pointer of the addrec SCEV is
978 // guaranteed to be loop invariant, which means that it should dominate the
979 // header. This allows us to insert code for it in the preheader.
980 BasicBlock *Preheader = CurLoop->getLoopPreheader();
981 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000982 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000983
Matt Arsenault11250c12013-09-11 05:09:42 +0000984 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
985
Chris Lattnera92ff912010-12-26 23:42:51 +0000986 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramer3740e792012-10-21 19:31:16 +0000987 // this into a memset in the loop preheader now if we want. However, this
988 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000989 // or write to the aliased location. Check for any overlap by generating the
990 // base pointer and checking the region.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000991 Value *BasePtr =
Matt Arsenault11250c12013-09-11 05:09:42 +0000992 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
Chris Lattnera92ff912010-12-26 23:42:51 +0000993 Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000994
Chandler Carrutha8647482012-11-02 08:33:25 +0000995 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
996 CurLoop, BECount,
Matt Arsenaultf834dce2013-09-11 05:09:35 +0000997 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
Chandler Carrutha8647482012-11-02 08:33:25 +0000998 Expander.clear();
999 // If we generated new code for the base pointer, clean up.
1000 deleteIfDeadInstruction(BasePtr, *SE, TLI);
1001 return false;
1002 }
1003
Chris Lattner4f81b542011-05-22 17:39:56 +00001004 // Okay, everything looks good, insert the memset.
1005
Chris Lattnera92ff912010-12-26 23:42:51 +00001006 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1007 // pointer size if it isn't already.
Stephen Hines36b56882014-04-23 16:57:46 -07001008 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner7c90b902011-01-04 00:06:55 +00001009 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001010
Chris Lattnera92ff912010-12-26 23:42:51 +00001011 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +00001012 SCEV::FlagNUW);
Matt Arsenaultf834dce2013-09-11 05:09:35 +00001013 if (StoreSize != 1) {
Chris Lattnera92ff912010-12-26 23:42:51 +00001014 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +00001015 SCEV::FlagNUW);
Matt Arsenaultf834dce2013-09-11 05:09:35 +00001016 }
Andrew Trickd99b39e2011-03-14 16:48:10 +00001017
1018 Value *NumBytes =
Chris Lattnera92ff912010-12-26 23:42:51 +00001019 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001020
Devang Patelcd77a502011-03-07 22:43:45 +00001021 CallInst *NewCall;
Matt Arsenaultf834dce2013-09-11 05:09:35 +00001022 if (SplatValue) {
1023 NewCall = Builder.CreateMemSet(BasePtr,
1024 SplatValue,
1025 NumBytes,
1026 StoreAlignment);
1027 } else {
Matt Arsenault11250c12013-09-11 05:09:42 +00001028 // Everything is emitted in default address space
1029 Type *Int8PtrTy = DestInt8PtrTy;
1030
Chris Lattner3a393722011-02-19 19:31:39 +00001031 Module *M = TheStore->getParent()->getParent()->getParent();
1032 Value *MSP = M->getOrInsertFunction("memset_pattern16",
1033 Builder.getVoidTy(),
Matt Arsenault11250c12013-09-11 05:09:42 +00001034 Int8PtrTy,
1035 Int8PtrTy,
1036 IntPtr,
Stephen Hinesdce4a402014-05-29 02:49:00 -07001037 (void*)nullptr);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001038
Chris Lattner3a393722011-02-19 19:31:39 +00001039 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1040 // an constant array of 16-bytes. Plop the value into a mergable global.
1041 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1042 GlobalValue::InternalLinkage,
1043 PatternValue, ".memset_pattern");
1044 GV->setUnnamedAddr(true); // Ok to merge these.
1045 GV->setAlignment(16);
Matt Arsenault11250c12013-09-11 05:09:42 +00001046 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
Chris Lattner3a393722011-02-19 19:31:39 +00001047 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1048 }
Andrew Trickd99b39e2011-03-14 16:48:10 +00001049
Chris Lattnera92ff912010-12-26 23:42:51 +00001050 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +00001051 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Patelcd77a502011-03-07 22:43:45 +00001052 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001053
Chris Lattner9f391882010-12-27 00:03:23 +00001054 // Okay, the memset has been formed. Zap the original store and anything that
1055 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001056 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner4ce31fb2011-01-02 07:36:44 +00001057 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +00001058 return true;
1059}
1060
Chris Lattnere2c43922011-01-02 03:37:56 +00001061/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1062/// same-strided load.
1063bool LoopIdiomRecognize::
1064processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1065 const SCEVAddRecExpr *StoreEv,
1066 const SCEVAddRecExpr *LoadEv,
1067 const SCEV *BECount) {
Chris Lattnerc19175c2011-02-18 22:22:15 +00001068 // If we're not allowed to form memcpy, we fail.
Chandler Carrutha8647482012-11-02 08:33:25 +00001069 if (!TLI->has(LibFunc::memcpy))
Chris Lattnerc19175c2011-02-18 22:22:15 +00001070 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +00001071
Chris Lattnere2c43922011-01-02 03:37:56 +00001072 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001073
Chris Lattner4f81b542011-05-22 17:39:56 +00001074 // The trip count of the loop and the base pointer of the addrec SCEV is
1075 // guaranteed to be loop invariant, which means that it should dominate the
1076 // header. This allows us to insert code for it in the preheader.
1077 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1078 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +00001079 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +00001080
Chris Lattnere2c43922011-01-02 03:37:56 +00001081 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carrutha8647482012-11-02 08:33:25 +00001082 // this into a memcpy in the loop preheader now if we want. However, this
1083 // would be unsafe to do if there is anything else in the loop that may read
1084 // or write the memory region we're storing to. This includes the load that
1085 // feeds the stores. Check for an alias by generating the base address and
1086 // checking everything.
Andrew Trickd99b39e2011-03-14 16:48:10 +00001087 Value *StoreBasePtr =
Chris Lattnere2c43922011-01-02 03:37:56 +00001088 Expander.expandCodeFor(StoreEv->getStart(),
1089 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1090 Preheader->getTerminator());
Chandler Carrutha8647482012-11-02 08:33:25 +00001091
1092 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1093 CurLoop, BECount, StoreSize,
1094 getAnalysis<AliasAnalysis>(), SI)) {
1095 Expander.clear();
1096 // If we generated new code for the base pointer, clean up.
1097 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1098 return false;
1099 }
1100
1101 // For a memcpy, we have to make sure that the input array is not being
1102 // mutated by the loop.
Chris Lattner4f81b542011-05-22 17:39:56 +00001103 Value *LoadBasePtr =
1104 Expander.expandCodeFor(LoadEv->getStart(),
1105 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1106 Preheader->getTerminator());
1107
Chandler Carrutha8647482012-11-02 08:33:25 +00001108 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1109 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1110 Expander.clear();
1111 // If we generated new code for the base pointer, clean up.
1112 deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1113 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1114 return false;
1115 }
1116
Chris Lattner4f81b542011-05-22 17:39:56 +00001117 // Okay, everything is safe, we can transform this!
Andrew Tricka5d950f2011-06-28 05:04:16 +00001118
Andrew Trickd99b39e2011-03-14 16:48:10 +00001119
Chris Lattnere2c43922011-01-02 03:37:56 +00001120 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1121 // pointer size if it isn't already.
Stephen Hines36b56882014-04-23 16:57:46 -07001122 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault11250c12013-09-11 05:09:42 +00001123 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001124
Matt Arsenault11250c12013-09-11 05:09:42 +00001125 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +00001126 SCEV::FlagNUW);
Chris Lattnere2c43922011-01-02 03:37:56 +00001127 if (StoreSize != 1)
Matt Arsenault11250c12013-09-11 05:09:42 +00001128 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +00001129 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +00001130
Chris Lattnere2c43922011-01-02 03:37:56 +00001131 Value *NumBytes =
Matt Arsenault11250c12013-09-11 05:09:42 +00001132 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001133
Chandler Carrutha8647482012-11-02 08:33:25 +00001134 CallInst *NewCall =
1135 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1136 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patelaf358412011-05-04 21:37:05 +00001137 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +00001138
Chandler Carrutha8647482012-11-02 08:33:25 +00001139 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattnere2c43922011-01-02 03:37:56 +00001140 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1141 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Tricka5d950f2011-06-28 05:04:16 +00001142
Andrew Trickd99b39e2011-03-14 16:48:10 +00001143
Chris Lattnere2c43922011-01-02 03:37:56 +00001144 // Okay, the memset has been formed. Zap the original store and anything that
1145 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001146 deleteDeadInstruction(SI, *SE, TLI);
Chandler Carrutha8647482012-11-02 08:33:25 +00001147 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +00001148 return true;
1149}