blob: ce425f1bf9fb9f5e1997273381a68802925671a1 [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 Lattner02a97762011-01-03 01:10:08 +000034// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000035// replace them with calls to BLAS (if linked in??).
36//
Chris Lattner0469e012011-01-02 18:32:09 +000037//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000038
Chris Lattner81ae3f22010-12-26 19:39:38 +000039#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000042#include "llvm/Analysis/BasicAliasAnalysis.h"
43#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000044#include "llvm/Analysis/LoopPass.h"
Chris Lattner29e14ed2010-12-26 23:42:51 +000045#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000046#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000049#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000050#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000058#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000059using namespace llvm;
60
Chandler Carruth964daaa2014-04-22 02:55:47 +000061#define DEBUG_TYPE "loop-idiom"
62
Chandler Carruth099f5cb02012-11-02 08:33:25 +000063STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000065
66namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000067
Chandler Carruthbad690e2015-08-12 23:06:37 +000068class LoopIdiomRecognize : public LoopPass {
69 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000070 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000071 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000072 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000073 ScalarEvolution *SE;
74 TargetLibraryInfo *TLI;
75 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +000076
Chandler Carruthbad690e2015-08-12 23:06:37 +000077public:
78 static char ID;
79 explicit LoopIdiomRecognize() : LoopPass(ID) {
80 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Chandler Carruthbad690e2015-08-12 23:06:37 +000081 }
Chris Lattner81ae3f22010-12-26 19:39:38 +000082
Chandler Carruthbad690e2015-08-12 23:06:37 +000083 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Shuxin Yang95de7c32012-12-09 03:12:46 +000084
Chandler Carruthbad690e2015-08-12 23:06:37 +000085 /// This transformation requires natural loop information & requires that
86 /// loop preheaders be inserted into the CFG.
87 ///
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.addRequired<LoopInfoWrapperPass>();
90 AU.addPreserved<LoopInfoWrapperPass>();
91 AU.addRequiredID(LoopSimplifyID);
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addRequiredID(LCSSAID);
94 AU.addPreservedID(LCSSAID);
Chandler Carruth7b560d42015-09-09 17:55:00 +000095 AU.addRequired<AAResultsWrapperPass>();
96 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000097 AU.addRequired<ScalarEvolutionWrapperPass>();
98 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +000099 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000100 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000101 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000102 AU.addRequired<TargetLibraryInfoWrapperPass>();
103 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000104 AU.addPreserved<BasicAAWrapperPass>();
105 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000106 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000107
Chandler Carruthbad690e2015-08-12 23:06:37 +0000108private:
Chandler Carruthd9c60702015-08-13 00:10:03 +0000109 /// \name Countable Loop Idiom Handling
110 /// @{
111
Chandler Carruthbad690e2015-08-12 23:06:37 +0000112 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000113 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
114 SmallVectorImpl<BasicBlock *> &ExitBlocks);
115
116 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
117 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
118
119 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
120 unsigned StoreAlignment, Value *SplatValue,
121 Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000122 const SCEV *BECount, bool NegStride);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000123 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
124 const SCEVAddRecExpr *StoreEv,
125 const SCEVAddRecExpr *LoadEv,
126 const SCEV *BECount);
127
128 /// @}
129 /// \name Noncountable Loop Idiom Handling
130 /// @{
131
132 bool runOnNoncountableLoop();
133
Chandler Carruth8219a502015-08-13 00:44:29 +0000134 bool recognizePopcount();
135 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
136 PHINode *CntPhi, Value *Var);
137
Chandler Carruthd9c60702015-08-13 00:10:03 +0000138 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000139};
140
141} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000142
143char LoopIdiomRecognize::ID = 0;
144INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
145 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000146INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000147INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000148INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
149INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000150INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000151INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000152INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
153INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
154INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
155INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000156INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000157INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
158 false, false)
159
160Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
161
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000162/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000163/// and zero out all the operands of this instruction. If any of them become
164/// dead, delete them and the computation tree that feeds them.
165///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000166static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000167 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000168 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
169 I->replaceAllUsesWith(UndefValue::get(I->getType()));
170 I->eraseFromParent();
171 for (Value *Op : Operands)
172 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000173}
174
Shuxin Yang95de7c32012-12-09 03:12:46 +0000175//===----------------------------------------------------------------------===//
176//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000177// Implementation of LoopIdiomRecognize
178//
179//===----------------------------------------------------------------------===//
180
Chandler Carruthd9c60702015-08-13 00:10:03 +0000181bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
182 if (skipOptnoneFunction(L))
183 return false;
184
185 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000186 // If the loop could not be converted to canonical form, it must have an
187 // indirectbr in it, just give up.
188 if (!L->getLoopPreheader())
189 return false;
190
191 // Disable loop idiom recognition if the function's name is a common idiom.
192 StringRef Name = L->getHeader()->getParent()->getName();
193 if (Name == "memset" || Name == "memcpy")
194 return false;
195
Chandler Carruth7b560d42015-09-09 17:55:00 +0000196 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthdc298322015-08-13 01:03:26 +0000197 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth18c26692015-08-13 09:27:01 +0000198 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000199 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthdc298322015-08-13 01:03:26 +0000200 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
201 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
202 *CurLoop->getHeader()->getParent());
203
Chandler Carruthd9c60702015-08-13 00:10:03 +0000204 if (SE->hasLoopInvariantBackedgeTakenCount(L))
205 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000206
Chandler Carruthd9c60702015-08-13 00:10:03 +0000207 return runOnNoncountableLoop();
208}
209
Shuxin Yang95de7c32012-12-09 03:12:46 +0000210bool LoopIdiomRecognize::runOnCountableLoop() {
211 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000212 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000213 "runOnCountableLoop() called on a loop without a predictable"
214 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000215
216 // If this loop executes exactly one time, then it should be peeled, not
217 // optimized by this pass.
218 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
219 if (BECst->getValue()->getValue() == 0)
220 return false;
221
Chandler Carruthbad690e2015-08-12 23:06:37 +0000222 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000223 CurLoop->getUniqueExitBlocks(ExitBlocks);
224
225 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000226 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
227 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000228
229 bool MadeChange = false;
230 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000231 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000232 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000233 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000234 continue;
235
Davide Italiano80625af2015-05-13 19:51:21 +0000236 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000237 }
238 return MadeChange;
239}
240
Chris Lattner8455b6e2011-01-02 19:01:03 +0000241/// runOnLoopBlock - Process the specified block, which lives in a counted loop
242/// with the specified backedge count. This block is known to be in the current
243/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000244bool LoopIdiomRecognize::runOnLoopBlock(
245 BasicBlock *BB, const SCEV *BECount,
246 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000247 // We can only promote stores in this block if they are unconditionally
248 // executed in the loop. For a block to be unconditionally executed, it has
249 // to dominate all the exit blocks of the loop. Verify this now.
250 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
251 if (!DT->dominates(BB, ExitBlocks[i]))
252 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000253
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000254 bool MadeChange = false;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000255 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000256 Instruction *Inst = &*I++;
Chris Lattnera62b01d2011-01-04 07:27:30 +0000257 // Look for store instructions, which may be optimized to memset/memcpy.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000258 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000259 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000260 if (!processLoopStore(SI, BECount))
261 continue;
Chris Lattnera62b01d2011-01-04 07:27:30 +0000262 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000263
Chris Lattnera62b01d2011-01-04 07:27:30 +0000264 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000265 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000266 if (!InstPtr)
Chris Lattnera62b01d2011-01-04 07:27:30 +0000267 I = BB->begin();
268 continue;
269 }
Andrew Trick328b2232011-03-14 16:48:10 +0000270
Chris Lattner86438102011-01-04 07:46:33 +0000271 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000272 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000273 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000274 if (!processLoopMemSet(MSI, BECount))
275 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000276 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000277
Chris Lattner86438102011-01-04 07:46:33 +0000278 // If processing the memset invalidated our iterator, start over from the
279 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000280 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000281 I = BB->begin();
282 continue;
283 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000284 }
Andrew Trick328b2232011-03-14 16:48:10 +0000285
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000286 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000287}
288
Chris Lattner86438102011-01-04 07:46:33 +0000289/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000290bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000291 if (!SI->isSimple())
292 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000293
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000294 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000295 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000296
Chris Lattner65a699d2010-12-28 18:53:48 +0000297 // Reject stores that are so large that they overflow an unsigned.
Mehdi Amini46a43552015-03-04 18:43:29 +0000298 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
299 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000300 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000301 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000302
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000303 // See if the pointer expression is an AddRec like {base,+,1} on the current
304 // loop, which indicates a strided store. If we have something else, it's a
305 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000306 const SCEVAddRecExpr *StoreEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000307 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000308 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000309 return false;
310
311 // Check to see if the stride matches the size of the store. If so, then we
312 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000313 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Andrew Trick328b2232011-03-14 16:48:10 +0000314
Chad Rosier79676142015-10-28 14:38:49 +0000315 const SCEVConstant *ConstStride =
316 dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
317 if (!ConstStride)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000318 return false;
Chad Rosier79676142015-10-28 14:38:49 +0000319
320 APInt Stride = ConstStride->getValue()->getValue();
321 if (StoreSize != Stride && StoreSize != -Stride)
322 return false;
323
324 bool NegStride = StoreSize == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000325
326 // See if we can optimize just this store in isolation.
327 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
Chad Rosier79676142015-10-28 14:38:49 +0000328 StoredVal, SI, StoreEv, BECount, NegStride))
Chris Lattner0f4a6402011-02-19 19:31:39 +0000329 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000330
Chad Rosier79676142015-10-28 14:38:49 +0000331 // TODO: We don't handle negative stride memcpys.
332 if (NegStride)
333 return false;
334
Chris Lattner85b6d812011-01-02 03:37:56 +0000335 // If the stored value is a strided load in the same loop with the same stride
336 // this this may be transformable into a memcpy. This kicks in for stuff like
337 // for (i) A[i] = B[i];
338 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
339 const SCEVAddRecExpr *LoadEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000340 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
Chris Lattner85b6d812011-01-02 03:37:56 +0000341 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000342 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000343 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
344 return true;
345 }
Chandler Carruthbad690e2015-08-12 23:06:37 +0000346 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000347
Chris Lattner81ae3f22010-12-26 19:39:38 +0000348 return false;
349}
350
Chris Lattner86438102011-01-04 07:46:33 +0000351/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000352bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
353 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000354 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000355 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
356 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000357
Chris Lattnere6b261f2011-02-18 22:22:15 +0000358 // If we're not allowed to hack on memset, we fail.
359 if (!TLI->has(LibFunc::memset))
360 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000361
Chris Lattner86438102011-01-04 07:46:33 +0000362 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000363
Chris Lattner86438102011-01-04 07:46:33 +0000364 // See if the pointer expression is an AddRec like {base,+,1} on the current
365 // loop, which indicates a strided store. If we have something else, it's a
366 // random store we can't handle.
367 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000368 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000369 return false;
370
371 // Reject memsets that are so large that they overflow an unsigned.
372 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
373 if ((SizeInBytes >> 32) != 0)
374 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000375
Chris Lattner86438102011-01-04 07:46:33 +0000376 // Check to see if the stride matches the size of the memset. If so, then we
377 // know that every byte is touched in the loop.
378 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000379
Chris Lattner86438102011-01-04 07:46:33 +0000380 // TODO: Could also handle negative stride here someday, that will require the
381 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000382 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000383 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000384
Chris Lattner0f4a6402011-02-19 19:31:39 +0000385 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Chandler Carruthbad690e2015-08-12 23:06:37 +0000386 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000387 BECount, /*NegStride=*/false);
Chris Lattner86438102011-01-04 07:46:33 +0000388}
389
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000390/// mayLoopAccessLocation - Return true if the specified loop might access the
391/// specified pointer location, which is a loop-strided access. The 'Access'
392/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000393static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
394 const SCEV *BECount, unsigned StoreSize,
395 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000396 Instruction *IgnoredStore) {
397 // Get the location that may be stored across the loop. Since the access is
398 // strided positively through memory, we say that the modified location starts
399 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000400 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000401
402 // If the loop iterates a fixed number of times, we can refine the access size
403 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
404 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000405 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000406
407 // TODO: For this to be really effective, we have to dive into the pointer
408 // operand in the store. Store to &A[i] of 100 will always return may alias
409 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
410 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000411 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000412
413 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
414 ++BI)
415 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000416 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000417 return true;
418
419 return false;
420}
421
Chris Lattner0f4a6402011-02-19 19:31:39 +0000422/// getMemSetPatternValue - If a strided store of the specified value is safe to
423/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
424/// be passed in. Otherwise, return null.
425///
426/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
427/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000428static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000429 // If the value isn't a constant, we can't promote it to being in a constant
430 // array. We could theoretically do a store to an alloca or something, but
431 // that doesn't seem worthwhile.
432 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000433 if (!C)
434 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000435
Chris Lattner0f4a6402011-02-19 19:31:39 +0000436 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000437 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000438 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000439 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000440
Chris Lattner72a35fb2011-02-19 19:56:44 +0000441 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000442 if (DL.isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000443 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000444
445 // Convert to size in bytes.
446 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000447
Chris Lattner0f4a6402011-02-19 19:31:39 +0000448 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000449 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000450 if (Size > 16)
451 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000452
Chris Lattner72a35fb2011-02-19 19:56:44 +0000453 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000454 if (Size == 16)
455 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000456
Chris Lattner72a35fb2011-02-19 19:56:44 +0000457 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000458 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000459 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000460 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000461}
462
Chris Lattner0f4a6402011-02-19 19:31:39 +0000463/// processLoopStridedStore - We see a strided store of some value. If we can
464/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000465bool LoopIdiomRecognize::processLoopStridedStore(
466 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
467 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000468 const SCEV *BECount, bool NegStride) {
Andrew Trick328b2232011-03-14 16:48:10 +0000469
Chris Lattner0f4a6402011-02-19 19:31:39 +0000470 // If the stored value is a byte-wise value (like i32 -1), then it may be
471 // turned into a memset of i8 -1, assuming that all the consecutive bytes
472 // are stored. A store of i32 0x01020304 can never be turned into a memset,
473 // but it can be turned into memset_pattern if the target supports it.
474 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000475 Constant *PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000476 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Matt Arsenault009faed2013-09-11 05:09:42 +0000477 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
478
Chris Lattner0f4a6402011-02-19 19:31:39 +0000479 // If we're allowed to form a memset, and the stored value would be acceptable
480 // for memset, use it.
481 if (SplatValue && TLI->has(LibFunc::memset) &&
482 // Verify that the stored value is loop invariant. If not, we can't
483 // promote the memset.
484 CurLoop->isLoopInvariant(SplatValue)) {
485 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000486 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000487 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
488 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000489 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000490 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000491 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000492 } else {
493 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000494 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000495 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000496 }
Andrew Trick328b2232011-03-14 16:48:10 +0000497
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000498 // The trip count of the loop and the base pointer of the addrec SCEV is
499 // guaranteed to be loop invariant, which means that it should dominate the
500 // header. This allows us to insert code for it in the preheader.
501 BasicBlock *Preheader = CurLoop->getLoopPreheader();
502 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000504
Matt Arsenault009faed2013-09-11 05:09:42 +0000505 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000506 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
507
508 const SCEV *Start = Ev->getStart();
509 // If we have a negative stride, Start refers to the end of the memory
510 // location we're trying to memset. Therefore, we need to recompute the start
511 // point, which is just Start - BECount*Size.
512 if (NegStride) {
513 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
514 if (StoreSize != 1)
515 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
516 SCEV::FlagNUW);
517 Start = SE->getMinusSCEV(Ev->getStart(), Index);
518 }
Matt Arsenault009faed2013-09-11 05:09:42 +0000519
Chris Lattner29e14ed2010-12-26 23:42:51 +0000520 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000521 // this into a memset in the loop preheader now if we want. However, this
522 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000523 // or write to the aliased location. Check for any overlap by generating the
524 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000525 Value *BasePtr =
526 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000527 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000528 *AA, TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000529 Expander.clear();
530 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000531 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000532 return false;
533 }
534
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000535 // Okay, everything looks good, insert the memset.
536
Chris Lattner29e14ed2010-12-26 23:42:51 +0000537 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
538 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000539 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000540
Chandler Carruthbad690e2015-08-12 23:06:37 +0000541 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000542 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000543 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000544 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000545 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000546 }
Andrew Trick328b2232011-03-14 16:48:10 +0000547
548 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000549 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000550
Devang Pateld00c6282011-03-07 22:43:45 +0000551 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000552 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000553 NewCall =
554 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000555 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000556 // Everything is emitted in default address space
557 Type *Int8PtrTy = DestInt8PtrTy;
558
Chris Lattner0f4a6402011-02-19 19:31:39 +0000559 Module *M = TheStore->getParent()->getParent()->getParent();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000560 Value *MSP =
561 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
562 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000563
Chris Lattner0f4a6402011-02-19 19:31:39 +0000564 // Otherwise we should form a memset_pattern16. PatternValue is known to be
565 // an constant array of 16-bytes. Plop the value into a mergable global.
566 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000567 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000568 PatternValue, ".memset_pattern");
569 GV->setUnnamedAddr(true); // Ok to merge these.
570 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000571 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000572 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000573 }
Andrew Trick328b2232011-03-14 16:48:10 +0000574
Chris Lattner29e14ed2010-12-26 23:42:51 +0000575 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000576 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000577 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000578
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000579 // Okay, the memset has been formed. Zap the original store and anything that
580 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000581 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000582 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000583 return true;
584}
585
Chris Lattner85b6d812011-01-02 03:37:56 +0000586/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
587/// same-strided load.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000588bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
589 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
590 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000591 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000592 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000593 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000594
Chris Lattner85b6d812011-01-02 03:37:56 +0000595 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +0000596
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000597 // The trip count of the loop and the base pointer of the addrec SCEV is
598 // guaranteed to be loop invariant, which means that it should dominate the
599 // header. This allows us to insert code for it in the preheader.
600 BasicBlock *Preheader = CurLoop->getLoopPreheader();
601 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000602 const DataLayout &DL = Preheader->getModule()->getDataLayout();
603 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000604
Chris Lattner85b6d812011-01-02 03:37:56 +0000605 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000606 // this into a memcpy in the loop preheader now if we want. However, this
607 // would be unsafe to do if there is anything else in the loop that may read
608 // or write the memory region we're storing to. This includes the load that
609 // feeds the stores. Check for an alias by generating the base address and
610 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000611 Value *StoreBasePtr = Expander.expandCodeFor(
612 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
613 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000614
Chandler Carruth194f59c2015-07-22 23:15:57 +0000615 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000616 StoreSize, *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000617 Expander.clear();
618 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000619 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000620 return false;
621 }
622
623 // For a memcpy, we have to make sure that the input array is not being
624 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000625 Value *LoadBasePtr = Expander.expandCodeFor(
626 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
627 Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000628
Chandler Carruth194f59c2015-07-22 23:15:57 +0000629 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000630 *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000631 Expander.clear();
632 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000633 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
634 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000635 return false;
636 }
637
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000638 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000639
Chris Lattner85b6d812011-01-02 03:37:56 +0000640 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
641 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000642 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +0000643 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000644
Chandler Carruthbad690e2015-08-12 23:06:37 +0000645 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000646 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000647 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000648 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000649 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000650
Chris Lattner85b6d812011-01-02 03:37:56 +0000651 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000652 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000653
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000654 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000655 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
656 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000657 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000658
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000659 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000660 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
661 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000662
Chad Rosier7f08d802015-10-13 20:59:16 +0000663 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000664 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000665 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000666 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000667 return true;
668}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000669
670bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000671 if (recognizePopcount())
Chandler Carruthd9c60702015-08-13 00:10:03 +0000672 return true;
673
674 return false;
675}
Chandler Carruth8219a502015-08-13 00:44:29 +0000676
677/// Check if the given conditional branch is based on the comparison between
678/// a variable and zero, and if the variable is non-zero, the control yields to
679/// the loop entry. If the branch matches the behavior, the variable involved
680/// in the comparion is returned. This function will be called to see if the
681/// precondition and postcondition of the loop are in desirable form.
682static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
683 if (!BI || !BI->isConditional())
684 return nullptr;
685
686 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
687 if (!Cond)
688 return nullptr;
689
690 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
691 if (!CmpZero || !CmpZero->isZero())
692 return nullptr;
693
694 ICmpInst::Predicate Pred = Cond->getPredicate();
695 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
696 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
697 return Cond->getOperand(0);
698
699 return nullptr;
700}
701
702/// Return true iff the idiom is detected in the loop.
703///
704/// Additionally:
705/// 1) \p CntInst is set to the instruction counting the population bit.
706/// 2) \p CntPhi is set to the corresponding phi node.
707/// 3) \p Var is set to the value whose population bits are being counted.
708///
709/// The core idiom we are trying to detect is:
710/// \code
711/// if (x0 != 0)
712/// goto loop-exit // the precondition of the loop
713/// cnt0 = init-val;
714/// do {
715/// x1 = phi (x0, x2);
716/// cnt1 = phi(cnt0, cnt2);
717///
718/// cnt2 = cnt1 + 1;
719/// ...
720/// x2 = x1 & (x1 - 1);
721/// ...
722/// } while(x != 0);
723///
724/// loop-exit:
725/// \endcode
726static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
727 Instruction *&CntInst, PHINode *&CntPhi,
728 Value *&Var) {
729 // step 1: Check to see if the look-back branch match this pattern:
730 // "if (a!=0) goto loop-entry".
731 BasicBlock *LoopEntry;
732 Instruction *DefX2, *CountInst;
733 Value *VarX1, *VarX0;
734 PHINode *PhiX, *CountPhi;
735
736 DefX2 = CountInst = nullptr;
737 VarX1 = VarX0 = nullptr;
738 PhiX = CountPhi = nullptr;
739 LoopEntry = *(CurLoop->block_begin());
740
741 // step 1: Check if the loop-back branch is in desirable form.
742 {
743 if (Value *T = matchCondition(
744 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
745 DefX2 = dyn_cast<Instruction>(T);
746 else
747 return false;
748 }
749
750 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
751 {
752 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
753 return false;
754
755 BinaryOperator *SubOneOp;
756
757 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
758 VarX1 = DefX2->getOperand(1);
759 else {
760 VarX1 = DefX2->getOperand(0);
761 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
762 }
763 if (!SubOneOp)
764 return false;
765
766 Instruction *SubInst = cast<Instruction>(SubOneOp);
767 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
768 if (!Dec ||
769 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
770 (SubInst->getOpcode() == Instruction::Add &&
771 Dec->isAllOnesValue()))) {
772 return false;
773 }
774 }
775
776 // step 3: Check the recurrence of variable X
777 {
778 PhiX = dyn_cast<PHINode>(VarX1);
779 if (!PhiX ||
780 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
781 return false;
782 }
783 }
784
785 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
786 {
787 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000788 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +0000789 IterE = LoopEntry->end();
790 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000791 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +0000792 if (Inst->getOpcode() != Instruction::Add)
793 continue;
794
795 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
796 if (!Inc || !Inc->isOne())
797 continue;
798
799 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
800 if (!Phi || Phi->getParent() != LoopEntry)
801 continue;
802
803 // Check if the result of the instruction is live of the loop.
804 bool LiveOutLoop = false;
805 for (User *U : Inst->users()) {
806 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
807 LiveOutLoop = true;
808 break;
809 }
810 }
811
812 if (LiveOutLoop) {
813 CountInst = Inst;
814 CountPhi = Phi;
815 break;
816 }
817 }
818
819 if (!CountInst)
820 return false;
821 }
822
823 // step 5: check if the precondition is in this form:
824 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
825 {
826 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
827 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
828 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
829 return false;
830
831 CntInst = CountInst;
832 CntPhi = CountPhi;
833 Var = T;
834 }
835
836 return true;
837}
838
839/// Recognizes a population count idiom in a non-countable loop.
840///
841/// If detected, transforms the relevant code to issue the popcount intrinsic
842/// function call, and returns true; otherwise, returns false.
843bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000844 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
845 return false;
846
847 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +0000848 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +0000849 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
850 // in a compact loop.
851
Renato Golin655348f2015-08-13 11:25:38 +0000852 // Give up if the loop has multiple blocks or multiple backedges.
853 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +0000854 return false;
855
Renato Golin655348f2015-08-13 11:25:38 +0000856 BasicBlock *LoopBody = *(CurLoop->block_begin());
857 if (LoopBody->size() >= 20) {
858 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +0000859 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000860 }
Chandler Carruth8219a502015-08-13 00:44:29 +0000861
862 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +0000863 BasicBlock *PH = CurLoop->getLoopPreheader();
864 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +0000865 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000866 if (&PH->front() != PH->getTerminator())
867 return false;
868 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +0000869 if (!EntryBI || EntryBI->isConditional())
870 return false;
871
872 // It should have a precondition block where the generated popcount instrinsic
873 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +0000874 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +0000875 if (!PreCondBB)
876 return false;
877 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
878 if (!PreCondBI || PreCondBI->isUnconditional())
879 return false;
880
881 Instruction *CntInst;
882 PHINode *CntPhi;
883 Value *Val;
884 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
885 return false;
886
887 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
888 return true;
889}
890
891static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
892 DebugLoc DL) {
893 Value *Ops[] = {Val};
894 Type *Tys[] = {Val->getType()};
895
896 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
897 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
898 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
899 CI->setDebugLoc(DL);
900
901 return CI;
902}
903
904void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
905 Instruction *CntInst,
906 PHINode *CntPhi, Value *Var) {
907 BasicBlock *PreHead = CurLoop->getLoopPreheader();
908 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
909 const DebugLoc DL = CntInst->getDebugLoc();
910
911 // Assuming before transformation, the loop is following:
912 // if (x) // the precondition
913 // do { cnt++; x &= x - 1; } while(x);
914
915 // Step 1: Insert the ctpop instruction at the end of the precondition block
916 IRBuilder<> Builder(PreCondBr);
917 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
918 {
919 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
920 NewCount = PopCntZext =
921 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
922
923 if (NewCount != PopCnt)
924 (cast<Instruction>(NewCount))->setDebugLoc(DL);
925
926 // TripCnt is exactly the number of iterations the loop has
927 TripCnt = NewCount;
928
929 // If the population counter's initial value is not zero, insert Add Inst.
930 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
931 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
932 if (!InitConst || !InitConst->isZero()) {
933 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
934 (cast<Instruction>(NewCount))->setDebugLoc(DL);
935 }
936 }
937
Nick Lewycky2c852542015-08-19 06:22:33 +0000938 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +0000939 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +0000940 // function would be partial dead code, and downstream passes will drag
941 // it back from the precondition block to the preheader.
942 {
943 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
944
945 Value *Opnd0 = PopCntZext;
946 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
947 if (PreCond->getOperand(0) != Var)
948 std::swap(Opnd0, Opnd1);
949
950 ICmpInst *NewPreCond = cast<ICmpInst>(
951 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
952 PreCondBr->setCondition(NewPreCond);
953
954 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
955 }
956
957 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +0000958 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +0000959 // loop into a countable one. The benefit is twofold:
960 //
Nick Lewycky2c852542015-08-19 06:22:33 +0000961 // - If the loop only counts population, the entire loop becomes dead after
962 // the transformation. It is a lot easier to prove a countable loop dead
963 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +0000964 // isn't dead even if it computes nothing useful. In general, DCE needs
965 // to prove a noncountable loop finite before safely delete it.)
966 //
967 // - If the loop also performs something else, it remains alive.
968 // Since it is transformed to countable form, it can be aggressively
969 // optimized by some optimizations which are in general not applicable
970 // to a noncountable loop.
971 //
972 // After this step, this loop (conceptually) would look like following:
973 // newcnt = __builtin_ctpop(x);
974 // t = newcnt;
975 // if (x)
976 // do { cnt++; x &= x-1; t--) } while (t > 0);
977 BasicBlock *Body = *(CurLoop->block_begin());
978 {
979 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
980 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
981 Type *Ty = TripCnt->getType();
982
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000983 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +0000984
985 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +0000986 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +0000987 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
988 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +0000989
990 TcPhi->addIncoming(TripCnt, PreHead);
991 TcPhi->addIncoming(TcDec, Body);
992
993 CmpInst::Predicate Pred =
994 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
995 LbCond->setPredicate(Pred);
996 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +0000997 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +0000998 }
999
1000 // Step 4: All the references to the original population counter outside
1001 // the loop are replaced with the NewCount -- the value returned from
1002 // __builtin_ctpop().
1003 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1004
1005 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1006 // loop. The loop would otherwise not be deleted even if it becomes empty.
1007 SE->forgetLoop(CurLoop);
1008}