blob: dee64091e55e4e83b7ef8e406e943ef7f346c753 [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
Chris Lattner81ae3f22010-12-26 19:39:38 +000044#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000046#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000047#include "llvm/Analysis/LoopPass.h"
Chris Lattner29e14ed2010-12-26 23:42:51 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Analysis/TargetLibraryInfo.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 Lattnerb9fe6852010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000061using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "loop-idiom"
64
Chandler Carruth099f5cb02012-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 Lattner81ae3f22010-12-26 19:39:38 +000067
68namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000069
Chandler Carruthbad690e2015-08-12 23:06:37 +000070class LoopIdiomRecognize : public LoopPass {
71 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000072 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000073 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000074 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000075 ScalarEvolution *SE;
76 TargetLibraryInfo *TLI;
77 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +000078
Chandler Carruthbad690e2015-08-12 23:06:37 +000079public:
80 static char ID;
81 explicit LoopIdiomRecognize() : LoopPass(ID) {
82 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Chandler Carruthbad690e2015-08-12 23:06:37 +000083 }
Chris Lattner81ae3f22010-12-26 19:39:38 +000084
Chandler Carruthbad690e2015-08-12 23:06:37 +000085 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Shuxin Yang95de7c32012-12-09 03:12:46 +000086
Chandler Carruthbad690e2015-08-12 23:06:37 +000087 /// This transformation requires natural loop information & requires that
88 /// loop preheaders be inserted into the CFG.
89 ///
90 void getAnalysisUsage(AnalysisUsage &AU) const override {
91 AU.addRequired<LoopInfoWrapperPass>();
92 AU.addPreserved<LoopInfoWrapperPass>();
93 AU.addRequiredID(LoopSimplifyID);
94 AU.addPreservedID(LoopSimplifyID);
95 AU.addRequiredID(LCSSAID);
96 AU.addPreservedID(LCSSAID);
97 AU.addRequired<AliasAnalysis>();
98 AU.addPreserved<AliasAnalysis>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000099 AU.addRequired<ScalarEvolutionWrapperPass>();
100 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000101 AU.addPreserved<DominatorTreeWrapperPass>();
102 AU.addRequired<DominatorTreeWrapperPass>();
103 AU.addRequired<TargetLibraryInfoWrapperPass>();
104 AU.addRequired<TargetTransformInfoWrapperPass>();
105 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000106
Chandler Carruthbad690e2015-08-12 23:06:37 +0000107private:
Chandler Carruthd9c60702015-08-13 00:10:03 +0000108 /// \name Countable Loop Idiom Handling
109 /// @{
110
Chandler Carruthbad690e2015-08-12 23:06:37 +0000111 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000112 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
113 SmallVectorImpl<BasicBlock *> &ExitBlocks);
114
115 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
116 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
117
118 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
119 unsigned StoreAlignment, Value *SplatValue,
120 Instruction *TheStore, const SCEVAddRecExpr *Ev,
121 const SCEV *BECount);
122 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
123 const SCEVAddRecExpr *StoreEv,
124 const SCEVAddRecExpr *LoadEv,
125 const SCEV *BECount);
126
127 /// @}
128 /// \name Noncountable Loop Idiom Handling
129 /// @{
130
131 bool runOnNoncountableLoop();
132
Chandler Carruth8219a502015-08-13 00:44:29 +0000133 bool recognizePopcount();
134 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
135 PHINode *CntPhi, Value *Var);
136
Chandler Carruthd9c60702015-08-13 00:10:03 +0000137 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000138};
139
140} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000141
142char LoopIdiomRecognize::ID = 0;
143INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
144 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000145INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000146INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000147INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
148INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000149INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000150INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000151INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth705b1852015-01-31 03:43:40 +0000152INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000153INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
154 false, false)
155
156Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
157
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000158/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000159/// and zero out all the operands of this instruction. If any of them become
160/// dead, delete them and the computation tree that feeds them.
161///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000162static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000163 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000164 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
165 I->replaceAllUsesWith(UndefValue::get(I->getType()));
166 I->eraseFromParent();
167 for (Value *Op : Operands)
168 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000169}
170
Shuxin Yang95de7c32012-12-09 03:12:46 +0000171//===----------------------------------------------------------------------===//
172//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000173// Implementation of LoopIdiomRecognize
174//
175//===----------------------------------------------------------------------===//
176
Chandler Carruthd9c60702015-08-13 00:10:03 +0000177bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
178 if (skipOptnoneFunction(L))
179 return false;
180
181 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000182 // If the loop could not be converted to canonical form, it must have an
183 // indirectbr in it, just give up.
184 if (!L->getLoopPreheader())
185 return false;
186
187 // Disable loop idiom recognition if the function's name is a common idiom.
188 StringRef Name = L->getHeader()->getParent()->getName();
189 if (Name == "memset" || Name == "memcpy")
190 return false;
191
Chandler Carruthbf143e22015-08-14 00:21:10 +0000192 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruthdc298322015-08-13 01:03:26 +0000193 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth18c26692015-08-13 09:27:01 +0000194 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000195 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthdc298322015-08-13 01:03:26 +0000196 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
197 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
198 *CurLoop->getHeader()->getParent());
199
Chandler Carruthd9c60702015-08-13 00:10:03 +0000200 if (SE->hasLoopInvariantBackedgeTakenCount(L))
201 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000202
Chandler Carruthd9c60702015-08-13 00:10:03 +0000203 return runOnNoncountableLoop();
204}
205
Shuxin Yang95de7c32012-12-09 03:12:46 +0000206bool LoopIdiomRecognize::runOnCountableLoop() {
207 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000208 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000209 "runOnCountableLoop() called on a loop without a predictable"
210 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000211
212 // If this loop executes exactly one time, then it should be peeled, not
213 // optimized by this pass.
214 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
215 if (BECst->getValue()->getValue() == 0)
216 return false;
217
Chandler Carruthbad690e2015-08-12 23:06:37 +0000218 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000219 CurLoop->getUniqueExitBlocks(ExitBlocks);
220
221 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000222 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
223 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000224
225 bool MadeChange = false;
226 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000227 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000228 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000229 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000230 continue;
231
Davide Italiano80625af2015-05-13 19:51:21 +0000232 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000233 }
234 return MadeChange;
235}
236
Chris Lattner8455b6e2011-01-02 19:01:03 +0000237/// runOnLoopBlock - Process the specified block, which lives in a counted loop
238/// with the specified backedge count. This block is known to be in the current
239/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000240bool LoopIdiomRecognize::runOnLoopBlock(
241 BasicBlock *BB, const SCEV *BECount,
242 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000243 // We can only promote stores in this block if they are unconditionally
244 // executed in the loop. For a block to be unconditionally executed, it has
245 // to dominate all the exit blocks of the loop. Verify this now.
246 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
247 if (!DT->dominates(BB, ExitBlocks[i]))
248 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000249
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000250 bool MadeChange = false;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000252 Instruction *Inst = I++;
253 // Look for store instructions, which may be optimized to memset/memcpy.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000254 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000255 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000256 if (!processLoopStore(SI, BECount))
257 continue;
Chris Lattnera62b01d2011-01-04 07:27:30 +0000258 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000259
Chris Lattnera62b01d2011-01-04 07:27:30 +0000260 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000261 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000262 if (!InstPtr)
Chris Lattnera62b01d2011-01-04 07:27:30 +0000263 I = BB->begin();
264 continue;
265 }
Andrew Trick328b2232011-03-14 16:48:10 +0000266
Chris Lattner86438102011-01-04 07:46:33 +0000267 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000268 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Chris Lattner86438102011-01-04 07:46:33 +0000269 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000270 if (!processLoopMemSet(MSI, BECount))
271 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000272 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000273
Chris Lattner86438102011-01-04 07:46:33 +0000274 // If processing the memset invalidated our iterator, start over from the
275 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000276 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000277 I = BB->begin();
278 continue;
279 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000280 }
Andrew Trick328b2232011-03-14 16:48:10 +0000281
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000282 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000283}
284
Chris Lattner86438102011-01-04 07:46:33 +0000285/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000286bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000287 if (!SI->isSimple())
288 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000289
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000290 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000291 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000292
Chris Lattner65a699d2010-12-28 18:53:48 +0000293 // Reject stores that are so large that they overflow an unsigned.
Mehdi Amini46a43552015-03-04 18:43:29 +0000294 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
295 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000296 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000297 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000298
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000299 // See if the pointer expression is an AddRec like {base,+,1} on the current
300 // loop, which indicates a strided store. If we have something else, it's a
301 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000302 const SCEVAddRecExpr *StoreEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000303 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000304 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000305 return false;
306
307 // Check to see if the stride matches the size of the store. If so, then we
308 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000309 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000310 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000311
Craig Topperf40110f2014-04-25 05:29:35 +0000312 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000313 // TODO: Could also handle negative stride here someday, that will require
314 // the validity check in mayLoopAccessLocation to be updated though.
315 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000316 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000317 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
318 dbgs() << "BB: " << *SI->getParent();
319 }
Andrew Trick328b2232011-03-14 16:48:10 +0000320
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000321 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000322 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000323
324 // See if we can optimize just this store in isolation.
325 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
326 StoredVal, SI, StoreEv, BECount))
327 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000328
Chris Lattner85b6d812011-01-02 03:37:56 +0000329 // If the stored value is a strided load in the same loop with the same stride
330 // this this may be transformable into a memcpy. This kicks in for stuff like
331 // for (i) A[i] = B[i];
332 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
333 const SCEVAddRecExpr *LoadEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000334 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
Chris Lattner85b6d812011-01-02 03:37:56 +0000335 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000336 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000337 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
338 return true;
339 }
Chandler Carruthbad690e2015-08-12 23:06:37 +0000340 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000341
Chris Lattner81ae3f22010-12-26 19:39:38 +0000342 return false;
343}
344
Chris Lattner86438102011-01-04 07:46:33 +0000345/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000346bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
347 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000348 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000349 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
350 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000351
Chris Lattnere6b261f2011-02-18 22:22:15 +0000352 // If we're not allowed to hack on memset, we fail.
353 if (!TLI->has(LibFunc::memset))
354 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000355
Chris Lattner86438102011-01-04 07:46:33 +0000356 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000357
Chris Lattner86438102011-01-04 07:46:33 +0000358 // See if the pointer expression is an AddRec like {base,+,1} on the current
359 // loop, which indicates a strided store. If we have something else, it's a
360 // random store we can't handle.
361 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000362 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000363 return false;
364
365 // Reject memsets that are so large that they overflow an unsigned.
366 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
367 if ((SizeInBytes >> 32) != 0)
368 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000369
Chris Lattner86438102011-01-04 07:46:33 +0000370 // Check to see if the stride matches the size of the memset. If so, then we
371 // know that every byte is touched in the loop.
372 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000373
Chris Lattner86438102011-01-04 07:46:33 +0000374 // TODO: Could also handle negative stride here someday, that will require the
375 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000376 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000377 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000378
Chris Lattner0f4a6402011-02-19 19:31:39 +0000379 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Chandler Carruthbad690e2015-08-12 23:06:37 +0000380 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
381 BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000382}
383
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000384/// mayLoopAccessLocation - Return true if the specified loop might access the
385/// specified pointer location, which is a loop-strided access. The 'Access'
386/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000387static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
388 const SCEV *BECount, unsigned StoreSize,
389 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000390 Instruction *IgnoredStore) {
391 // Get the location that may be stored across the loop. Since the access is
392 // strided positively through memory, we say that the modified location starts
393 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000394 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000395
396 // If the loop iterates a fixed number of times, we can refine the access size
397 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
398 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000399 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000400
401 // TODO: For this to be really effective, we have to dive into the pointer
402 // operand in the store. Store to &A[i] of 100 will always return may alias
403 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
404 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000405 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000406
407 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
408 ++BI)
409 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chandler Carruthbad690e2015-08-12 23:06:37 +0000410 if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000411 return true;
412
413 return false;
414}
415
Chris Lattner0f4a6402011-02-19 19:31:39 +0000416/// getMemSetPatternValue - If a strided store of the specified value is safe to
417/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
418/// be passed in. Otherwise, return null.
419///
420/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
421/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000422static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000423 // If the value isn't a constant, we can't promote it to being in a constant
424 // array. We could theoretically do a store to an alloca or something, but
425 // that doesn't seem worthwhile.
426 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000427 if (!C)
428 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000429
Chris Lattner0f4a6402011-02-19 19:31:39 +0000430 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000431 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000432 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000433 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000434
Chris Lattner72a35fb2011-02-19 19:56:44 +0000435 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000436 if (DL.isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000437 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000438
439 // Convert to size in bytes.
440 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000441
Chris Lattner0f4a6402011-02-19 19:31:39 +0000442 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000443 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000444 if (Size > 16)
445 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000446
Chris Lattner72a35fb2011-02-19 19:56:44 +0000447 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000448 if (Size == 16)
449 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000450
Chris Lattner72a35fb2011-02-19 19:56:44 +0000451 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000452 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000453 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000454 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000455}
456
Chris Lattner0f4a6402011-02-19 19:31:39 +0000457/// processLoopStridedStore - We see a strided store of some value. If we can
458/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000459bool LoopIdiomRecognize::processLoopStridedStore(
460 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
461 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
462 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000463
Chris Lattner0f4a6402011-02-19 19:31:39 +0000464 // If the stored value is a byte-wise value (like i32 -1), then it may be
465 // turned into a memset of i8 -1, assuming that all the consecutive bytes
466 // are stored. A store of i32 0x01020304 can never be turned into a memset,
467 // but it can be turned into memset_pattern if the target supports it.
468 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000469 Constant *PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000470 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Matt Arsenault009faed2013-09-11 05:09:42 +0000471 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
472
Chris Lattner0f4a6402011-02-19 19:31:39 +0000473 // If we're allowed to form a memset, and the stored value would be acceptable
474 // for memset, use it.
475 if (SplatValue && TLI->has(LibFunc::memset) &&
476 // Verify that the stored value is loop invariant. If not, we can't
477 // promote the memset.
478 CurLoop->isLoopInvariant(SplatValue)) {
479 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000480 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000481 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
482 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000483 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000484 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000485 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000486 } else {
487 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000488 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000489 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000490 }
Andrew Trick328b2232011-03-14 16:48:10 +0000491
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000492 // The trip count of the loop and the base pointer of the addrec SCEV is
493 // guaranteed to be loop invariant, which means that it should dominate the
494 // header. This allows us to insert code for it in the preheader.
495 BasicBlock *Preheader = CurLoop->getLoopPreheader();
496 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000498
Matt Arsenault009faed2013-09-11 05:09:42 +0000499 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
500
Chris Lattner29e14ed2010-12-26 23:42:51 +0000501 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000502 // this into a memset in the loop preheader now if we want. However, this
503 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000504 // or write to the aliased location. Check for any overlap by generating the
505 // base pointer and checking the region.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000506 Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
507 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000508
Chandler Carruth194f59c2015-07-22 23:15:57 +0000509 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000510 *AA, TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000511 Expander.clear();
512 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000513 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000514 return false;
515 }
516
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000517 // Okay, everything looks good, insert the memset.
518
Chris Lattner29e14ed2010-12-26 23:42:51 +0000519 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
520 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000521 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +0000522 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000523
Chandler Carruthbad690e2015-08-12 23:06:37 +0000524 const SCEV *NumBytesS =
525 SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000526 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000527 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000528 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000529 }
Andrew Trick328b2232011-03-14 16:48:10 +0000530
531 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000532 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000533
Devang Pateld00c6282011-03-07 22:43:45 +0000534 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000535 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000536 NewCall =
537 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000538 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000539 // Everything is emitted in default address space
540 Type *Int8PtrTy = DestInt8PtrTy;
541
Chris Lattner0f4a6402011-02-19 19:31:39 +0000542 Module *M = TheStore->getParent()->getParent()->getParent();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000543 Value *MSP =
544 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
545 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000546
Chris Lattner0f4a6402011-02-19 19:31:39 +0000547 // Otherwise we should form a memset_pattern16. PatternValue is known to be
548 // an constant array of 16-bytes. Plop the value into a mergable global.
549 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000550 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000551 PatternValue, ".memset_pattern");
552 GV->setUnnamedAddr(true); // Ok to merge these.
553 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000554 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000555 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000556 }
Andrew Trick328b2232011-03-14 16:48:10 +0000557
Chris Lattner29e14ed2010-12-26 23:42:51 +0000558 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000559 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000560 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000561
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000562 // Okay, the memset has been formed. Zap the original store and anything that
563 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000564 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000565 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000566 return true;
567}
568
Chris Lattner85b6d812011-01-02 03:37:56 +0000569/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
570/// same-strided load.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000571bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
572 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
573 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000574 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000575 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000576 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000577
Chris Lattner85b6d812011-01-02 03:37:56 +0000578 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +0000579
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000580 // The trip count of the loop and the base pointer of the addrec SCEV is
581 // guaranteed to be loop invariant, which means that it should dominate the
582 // header. This allows us to insert code for it in the preheader.
583 BasicBlock *Preheader = CurLoop->getLoopPreheader();
584 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 const DataLayout &DL = Preheader->getModule()->getDataLayout();
586 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000587
Chris Lattner85b6d812011-01-02 03:37:56 +0000588 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000589 // this into a memcpy in the loop preheader now if we want. However, this
590 // would be unsafe to do if there is anything else in the loop that may read
591 // or write the memory region we're storing to. This includes the load that
592 // feeds the stores. Check for an alias by generating the base address and
593 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000594 Value *StoreBasePtr = Expander.expandCodeFor(
595 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
596 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000597
Chandler Carruth194f59c2015-07-22 23:15:57 +0000598 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000599 StoreSize, *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000600 Expander.clear();
601 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000602 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000603 return false;
604 }
605
606 // For a memcpy, we have to make sure that the input array is not being
607 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000608 Value *LoadBasePtr = Expander.expandCodeFor(
609 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
610 Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000611
Chandler Carruth194f59c2015-07-22 23:15:57 +0000612 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000613 *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000614 Expander.clear();
615 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000616 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
617 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000618 return false;
619 }
620
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000621 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000622
Chris Lattner85b6d812011-01-02 03:37:56 +0000623 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
624 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +0000626 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000627
Chandler Carruthbad690e2015-08-12 23:06:37 +0000628 const SCEV *NumBytesS =
629 SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000630 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000631 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000632 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000633
Chris Lattner85b6d812011-01-02 03:37:56 +0000634 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000635 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000636
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000637 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000638 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
639 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000640 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000641
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000642 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000643 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
644 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000645
Chris Lattner85b6d812011-01-02 03:37:56 +0000646 // Okay, the memset has been formed. Zap the original store and anything that
647 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000648 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000649 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000650 return true;
651}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000652
653bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000654 if (recognizePopcount())
Chandler Carruthd9c60702015-08-13 00:10:03 +0000655 return true;
656
657 return false;
658}
Chandler Carruth8219a502015-08-13 00:44:29 +0000659
660/// Check if the given conditional branch is based on the comparison between
661/// a variable and zero, and if the variable is non-zero, the control yields to
662/// the loop entry. If the branch matches the behavior, the variable involved
663/// in the comparion is returned. This function will be called to see if the
664/// precondition and postcondition of the loop are in desirable form.
665static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
666 if (!BI || !BI->isConditional())
667 return nullptr;
668
669 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
670 if (!Cond)
671 return nullptr;
672
673 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
674 if (!CmpZero || !CmpZero->isZero())
675 return nullptr;
676
677 ICmpInst::Predicate Pred = Cond->getPredicate();
678 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
679 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
680 return Cond->getOperand(0);
681
682 return nullptr;
683}
684
685/// Return true iff the idiom is detected in the loop.
686///
687/// Additionally:
688/// 1) \p CntInst is set to the instruction counting the population bit.
689/// 2) \p CntPhi is set to the corresponding phi node.
690/// 3) \p Var is set to the value whose population bits are being counted.
691///
692/// The core idiom we are trying to detect is:
693/// \code
694/// if (x0 != 0)
695/// goto loop-exit // the precondition of the loop
696/// cnt0 = init-val;
697/// do {
698/// x1 = phi (x0, x2);
699/// cnt1 = phi(cnt0, cnt2);
700///
701/// cnt2 = cnt1 + 1;
702/// ...
703/// x2 = x1 & (x1 - 1);
704/// ...
705/// } while(x != 0);
706///
707/// loop-exit:
708/// \endcode
709static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
710 Instruction *&CntInst, PHINode *&CntPhi,
711 Value *&Var) {
712 // step 1: Check to see if the look-back branch match this pattern:
713 // "if (a!=0) goto loop-entry".
714 BasicBlock *LoopEntry;
715 Instruction *DefX2, *CountInst;
716 Value *VarX1, *VarX0;
717 PHINode *PhiX, *CountPhi;
718
719 DefX2 = CountInst = nullptr;
720 VarX1 = VarX0 = nullptr;
721 PhiX = CountPhi = nullptr;
722 LoopEntry = *(CurLoop->block_begin());
723
724 // step 1: Check if the loop-back branch is in desirable form.
725 {
726 if (Value *T = matchCondition(
727 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
728 DefX2 = dyn_cast<Instruction>(T);
729 else
730 return false;
731 }
732
733 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
734 {
735 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
736 return false;
737
738 BinaryOperator *SubOneOp;
739
740 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
741 VarX1 = DefX2->getOperand(1);
742 else {
743 VarX1 = DefX2->getOperand(0);
744 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
745 }
746 if (!SubOneOp)
747 return false;
748
749 Instruction *SubInst = cast<Instruction>(SubOneOp);
750 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
751 if (!Dec ||
752 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
753 (SubInst->getOpcode() == Instruction::Add &&
754 Dec->isAllOnesValue()))) {
755 return false;
756 }
757 }
758
759 // step 3: Check the recurrence of variable X
760 {
761 PhiX = dyn_cast<PHINode>(VarX1);
762 if (!PhiX ||
763 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
764 return false;
765 }
766 }
767
768 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
769 {
770 CountInst = nullptr;
771 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
772 IterE = LoopEntry->end();
773 Iter != IterE; Iter++) {
774 Instruction *Inst = Iter;
775 if (Inst->getOpcode() != Instruction::Add)
776 continue;
777
778 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
779 if (!Inc || !Inc->isOne())
780 continue;
781
782 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
783 if (!Phi || Phi->getParent() != LoopEntry)
784 continue;
785
786 // Check if the result of the instruction is live of the loop.
787 bool LiveOutLoop = false;
788 for (User *U : Inst->users()) {
789 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
790 LiveOutLoop = true;
791 break;
792 }
793 }
794
795 if (LiveOutLoop) {
796 CountInst = Inst;
797 CountPhi = Phi;
798 break;
799 }
800 }
801
802 if (!CountInst)
803 return false;
804 }
805
806 // step 5: check if the precondition is in this form:
807 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
808 {
809 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
810 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
811 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
812 return false;
813
814 CntInst = CountInst;
815 CntPhi = CountPhi;
816 Var = T;
817 }
818
819 return true;
820}
821
822/// Recognizes a population count idiom in a non-countable loop.
823///
824/// If detected, transforms the relevant code to issue the popcount intrinsic
825/// function call, and returns true; otherwise, returns false.
826bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000827 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
828 return false;
829
830 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +0000831 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +0000832 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
833 // in a compact loop.
834
Renato Golin655348f2015-08-13 11:25:38 +0000835 // Give up if the loop has multiple blocks or multiple backedges.
836 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +0000837 return false;
838
Renato Golin655348f2015-08-13 11:25:38 +0000839 BasicBlock *LoopBody = *(CurLoop->block_begin());
840 if (LoopBody->size() >= 20) {
841 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +0000842 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000843 }
Chandler Carruth8219a502015-08-13 00:44:29 +0000844
845 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +0000846 BasicBlock *PH = CurLoop->getLoopPreheader();
847 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +0000848 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000849 if (&PH->front() != PH->getTerminator())
850 return false;
851 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +0000852 if (!EntryBI || EntryBI->isConditional())
853 return false;
854
855 // It should have a precondition block where the generated popcount instrinsic
856 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +0000857 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +0000858 if (!PreCondBB)
859 return false;
860 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
861 if (!PreCondBI || PreCondBI->isUnconditional())
862 return false;
863
864 Instruction *CntInst;
865 PHINode *CntPhi;
866 Value *Val;
867 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
868 return false;
869
870 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
871 return true;
872}
873
874static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
875 DebugLoc DL) {
876 Value *Ops[] = {Val};
877 Type *Tys[] = {Val->getType()};
878
879 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
880 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
881 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
882 CI->setDebugLoc(DL);
883
884 return CI;
885}
886
887void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
888 Instruction *CntInst,
889 PHINode *CntPhi, Value *Var) {
890 BasicBlock *PreHead = CurLoop->getLoopPreheader();
891 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
892 const DebugLoc DL = CntInst->getDebugLoc();
893
894 // Assuming before transformation, the loop is following:
895 // if (x) // the precondition
896 // do { cnt++; x &= x - 1; } while(x);
897
898 // Step 1: Insert the ctpop instruction at the end of the precondition block
899 IRBuilder<> Builder(PreCondBr);
900 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
901 {
902 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
903 NewCount = PopCntZext =
904 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
905
906 if (NewCount != PopCnt)
907 (cast<Instruction>(NewCount))->setDebugLoc(DL);
908
909 // TripCnt is exactly the number of iterations the loop has
910 TripCnt = NewCount;
911
912 // If the population counter's initial value is not zero, insert Add Inst.
913 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
914 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
915 if (!InitConst || !InitConst->isZero()) {
916 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
917 (cast<Instruction>(NewCount))->setDebugLoc(DL);
918 }
919 }
920
Nick Lewycky2c852542015-08-19 06:22:33 +0000921 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
922 // "if (NewCount == 0) loop-exit". Withtout this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +0000923 // function would be partial dead code, and downstream passes will drag
924 // it back from the precondition block to the preheader.
925 {
926 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
927
928 Value *Opnd0 = PopCntZext;
929 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
930 if (PreCond->getOperand(0) != Var)
931 std::swap(Opnd0, Opnd1);
932
933 ICmpInst *NewPreCond = cast<ICmpInst>(
934 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
935 PreCondBr->setCondition(NewPreCond);
936
937 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
938 }
939
940 // Step 3: Note that the population count is exactly the trip count of the
941 // loop in question, which enble us to to convert the loop from noncountable
942 // loop into a countable one. The benefit is twofold:
943 //
Nick Lewycky2c852542015-08-19 06:22:33 +0000944 // - If the loop only counts population, the entire loop becomes dead after
945 // the transformation. It is a lot easier to prove a countable loop dead
946 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +0000947 // isn't dead even if it computes nothing useful. In general, DCE needs
948 // to prove a noncountable loop finite before safely delete it.)
949 //
950 // - If the loop also performs something else, it remains alive.
951 // Since it is transformed to countable form, it can be aggressively
952 // optimized by some optimizations which are in general not applicable
953 // to a noncountable loop.
954 //
955 // After this step, this loop (conceptually) would look like following:
956 // newcnt = __builtin_ctpop(x);
957 // t = newcnt;
958 // if (x)
959 // do { cnt++; x &= x-1; t--) } while (t > 0);
960 BasicBlock *Body = *(CurLoop->block_begin());
961 {
962 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
963 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
964 Type *Ty = TripCnt->getType();
965
966 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
967
968 Builder.SetInsertPoint(LbCond);
Nick Lewycky2c852542015-08-19 06:22:33 +0000969 Value *Opnd1 = TcPhi;
970 Value *Opnd2 = ConstantInt::get(Ty, 1);
Chandler Carruth8219a502015-08-13 00:44:29 +0000971 Instruction *TcDec = cast<Instruction>(
972 Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
973
974 TcPhi->addIncoming(TripCnt, PreHead);
975 TcPhi->addIncoming(TcDec, Body);
976
977 CmpInst::Predicate Pred =
978 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
979 LbCond->setPredicate(Pred);
980 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +0000981 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +0000982 }
983
984 // Step 4: All the references to the original population counter outside
985 // the loop are replaced with the NewCount -- the value returned from
986 // __builtin_ctpop().
987 CntInst->replaceUsesOutsideBlock(NewCount, Body);
988
989 // step 5: Forget the "non-computable" trip-count SCEV associated with the
990 // loop. The loop would otherwise not be deleted even if it becomes empty.
991 SE->forgetLoop(CurLoop);
992}