blob: 68bd672c6093d0e5762d97d34689675d28b01fdd [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//
Chris Lattner02a97762011-01-03 01:10:08 +000029// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000030// replace them with calls to BLAS (if linked in??).
31//
Chris Lattner0469e012011-01-02 18:32:09 +000032//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000033
Chris Lattner81ae3f22010-12-26 19:39:38 +000034#include "llvm/Transforms/Scalar.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000035#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/SetVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000038#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000039#include "llvm/Analysis/BasicAliasAnalysis.h"
40#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000041#include "llvm/Analysis/LoopPass.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000042#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000043#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000044#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000047#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000048#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000054#include "llvm/Support/Debug.h"
55#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000056#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000057#include "llvm/Transforms/Utils/LoopUtils.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000058using namespace llvm;
59
Chandler Carruth964daaa2014-04-22 02:55:47 +000060#define DEBUG_TYPE "loop-idiom"
61
Chandler Carruth099f5cb02012-11-02 08:33:25 +000062STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
63STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000064
65namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000066
Chandler Carruthbad690e2015-08-12 23:06:37 +000067class LoopIdiomRecognize : public LoopPass {
68 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000069 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000070 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000071 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000072 ScalarEvolution *SE;
73 TargetLibraryInfo *TLI;
74 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +000075 const DataLayout *DL;
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 {
Chandler Carruthbad690e2015-08-12 23:06:37 +000089 AU.addRequired<TargetLibraryInfoWrapperPass>();
90 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +000091 getLoopAnalysisUsage(AU);
Chandler Carruthbad690e2015-08-12 23:06:37 +000092 }
Shuxin Yang95de7c32012-12-09 03:12:46 +000093
Chandler Carruthbad690e2015-08-12 23:06:37 +000094private:
Chad Rosiercc9030b2015-11-11 23:00:59 +000095 typedef SmallVector<StoreInst *, 8> StoreList;
Haicheng Wuf1c00a22016-01-26 02:27:47 +000096 typedef MapVector<Value *, StoreList> StoreListMap;
97 StoreListMap StoreRefsForMemset;
98 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +000099 StoreList StoreRefsForMemcpy;
100 bool HasMemset;
101 bool HasMemsetPattern;
102 bool HasMemcpy;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000103
Chandler Carruthd9c60702015-08-13 00:10:03 +0000104 /// \name Countable Loop Idiom Handling
105 /// @{
106
Chandler Carruthbad690e2015-08-12 23:06:37 +0000107 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000108 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
109 SmallVectorImpl<BasicBlock *> &ExitBlocks);
110
Chad Rosiercc9030b2015-11-11 23:00:59 +0000111 void collectStores(BasicBlock *BB);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000112 bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern,
113 bool &ForMemcpy);
114 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
115 bool ForMemset);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000116 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
117
118 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000119 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000120 Instruction *TheStore,
121 SmallPtrSetImpl<Instruction *> &Stores,
122 const SCEVAddRecExpr *Ev, const SCEV *BECount,
123 bool NegStride);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000124 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000125
126 /// @}
127 /// \name Noncountable Loop Idiom Handling
128 /// @{
129
130 bool runOnNoncountableLoop();
131
Chandler Carruth8219a502015-08-13 00:44:29 +0000132 bool recognizePopcount();
133 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
134 PHINode *CntPhi, Value *Var);
135
Chandler Carruthd9c60702015-08-13 00:10:03 +0000136 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000137};
138
139} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000140
141char LoopIdiomRecognize::ID = 0;
142INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
143 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000144INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000145INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000146INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000147INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
148 false, false)
149
150Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
151
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000152/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000153/// and zero out all the operands of this instruction. If any of them become
154/// dead, delete them and the computation tree that feeds them.
155///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000156static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000157 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000158 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
159 I->replaceAllUsesWith(UndefValue::get(I->getType()));
160 I->eraseFromParent();
161 for (Value *Op : Operands)
162 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000163}
164
Shuxin Yang95de7c32012-12-09 03:12:46 +0000165//===----------------------------------------------------------------------===//
166//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000167// Implementation of LoopIdiomRecognize
168//
169//===----------------------------------------------------------------------===//
170
Chandler Carruthd9c60702015-08-13 00:10:03 +0000171bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000172 if (skipLoop(L))
Chandler Carruthd9c60702015-08-13 00:10:03 +0000173 return false;
174
175 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000176 // If the loop could not be converted to canonical form, it must have an
177 // indirectbr in it, just give up.
178 if (!L->getLoopPreheader())
179 return false;
180
181 // Disable loop idiom recognition if the function's name is a common idiom.
182 StringRef Name = L->getHeader()->getParent()->getName();
183 if (Name == "memset" || Name == "memcpy")
184 return false;
185
Chandler Carruth7b560d42015-09-09 17:55:00 +0000186 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthdc298322015-08-13 01:03:26 +0000187 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth18c26692015-08-13 09:27:01 +0000188 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000189 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthdc298322015-08-13 01:03:26 +0000190 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
191 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
192 *CurLoop->getHeader()->getParent());
Chad Rosier43f9b482015-11-06 16:33:57 +0000193 DL = &CurLoop->getHeader()->getModule()->getDataLayout();
Chandler Carruthdc298322015-08-13 01:03:26 +0000194
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000195 HasMemset = TLI->has(LibFunc::memset);
196 HasMemsetPattern = TLI->has(LibFunc::memset_pattern16);
197 HasMemcpy = TLI->has(LibFunc::memcpy);
198
199 if (HasMemset || HasMemsetPattern || HasMemcpy)
200 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))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000215 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000216 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
Chad Rosiera548fe52015-11-12 19:09:16 +0000237static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
238 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
239 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
240 "Don't overflow unsigned.");
241 return (unsigned)SizeInBits >> 3;
242}
243
Chad Rosier4acff962016-02-12 19:05:27 +0000244static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000245 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000246 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000247}
248
Chad Rosier94274fb2015-12-21 14:49:32 +0000249/// getMemSetPatternValue - If a strided store of the specified value is safe to
250/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
251/// be passed in. Otherwise, return null.
252///
253/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
254/// just replicate their input array and then pass on to memset_pattern16.
255static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
256 // If the value isn't a constant, we can't promote it to being in a constant
257 // array. We could theoretically do a store to an alloca or something, but
258 // that doesn't seem worthwhile.
259 Constant *C = dyn_cast<Constant>(V);
260 if (!C)
261 return nullptr;
262
263 // Only handle simple values that are a power of two bytes in size.
264 uint64_t Size = DL->getTypeSizeInBits(V->getType());
265 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
266 return nullptr;
267
268 // Don't care enough about darwin/ppc to implement this.
269 if (DL->isBigEndian())
270 return nullptr;
271
272 // Convert to size in bytes.
273 Size /= 8;
274
275 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
276 // if the top and bottom are the same (e.g. for vectors and large integers).
277 if (Size > 16)
278 return nullptr;
279
280 // If the constant is exactly 16 bytes, just use it.
281 if (Size == 16)
282 return C;
283
284 // Otherwise, we'll use an array of the constants.
285 unsigned ArraySize = 16 / Size;
286 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
287 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
288}
289
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000290bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000291 bool &ForMemsetPattern, bool &ForMemcpy) {
Chad Rosier869962f2015-12-01 14:26:35 +0000292 // Don't touch volatile stores.
293 if (!SI->isSimple())
294 return false;
295
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000296 // Avoid merging nontemporal stores.
297 if (SI->getMetadata(LLVMContext::MD_nontemporal))
298 return false;
299
Chad Rosiera548fe52015-11-12 19:09:16 +0000300 Value *StoredVal = SI->getValueOperand();
301 Value *StorePtr = SI->getPointerOperand();
302
303 // Reject stores that are so large that they overflow an unsigned.
304 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
305 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
306 return false;
307
308 // See if the pointer expression is an AddRec like {base,+,1} on the current
309 // loop, which indicates a strided store. If we have something else, it's a
310 // random store we can't handle.
311 const SCEVAddRecExpr *StoreEv =
312 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
313 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
314 return false;
315
316 // Check to see if we have a constant stride.
317 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
318 return false;
319
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000320 // See if the store can be turned into a memset.
321
322 // If the stored value is a byte-wise value (like i32 -1), then it may be
323 // turned into a memset of i8 -1, assuming that all the consecutive bytes
324 // are stored. A store of i32 0x01020304 can never be turned into a memset,
325 // but it can be turned into memset_pattern if the target supports it.
326 Value *SplatValue = isBytewiseValue(StoredVal);
327 Constant *PatternValue = nullptr;
328
329 // If we're allowed to form a memset, and the stored value would be
330 // acceptable for memset, use it.
331 if (HasMemset && SplatValue &&
332 // Verify that the stored value is loop invariant. If not, we can't
333 // promote the memset.
334 CurLoop->isLoopInvariant(SplatValue)) {
335 // It looks like we can use SplatValue.
336 ForMemset = true;
337 return true;
338 } else if (HasMemsetPattern &&
339 // Don't create memset_pattern16s with address spaces.
340 StorePtr->getType()->getPointerAddressSpace() == 0 &&
341 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
342 // It looks like we can use PatternValue!
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000343 ForMemsetPattern = true;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000344 return true;
345 }
346
347 // Otherwise, see if the store can be turned into a memcpy.
348 if (HasMemcpy) {
349 // Check to see if the stride matches the size of the store. If so, then we
350 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000351 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000352 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
353 if (StoreSize != Stride && StoreSize != -Stride)
354 return false;
355
356 // The store must be feeding a non-volatile load.
357 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
358 if (!LI || !LI->isSimple())
359 return false;
360
361 // See if the pointer expression is an AddRec like {base,+,1} on the current
362 // loop, which indicates a strided load. If we have something else, it's a
363 // random load we can't handle.
364 const SCEVAddRecExpr *LoadEv =
365 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
366 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
367 return false;
368
369 // The store and load must share the same stride.
370 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
371 return false;
372
373 // Success. This store can be converted into a memcpy.
374 ForMemcpy = true;
375 return true;
376 }
377 // This store can't be transformed into a memset/memcpy.
378 return false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000379}
380
Chad Rosiercc9030b2015-11-11 23:00:59 +0000381void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000382 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000383 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000384 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000385 for (Instruction &I : *BB) {
386 StoreInst *SI = dyn_cast<StoreInst>(&I);
387 if (!SI)
388 continue;
389
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000390 bool ForMemset = false;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000391 bool ForMemsetPattern = false;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000392 bool ForMemcpy = false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000393 // Make sure this is a strided store with a constant stride.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000394 if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy))
Chad Rosiera548fe52015-11-12 19:09:16 +0000395 continue;
396
Chad Rosiercc9030b2015-11-11 23:00:59 +0000397 // Save the store locations.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000398 if (ForMemset) {
399 // Find the base pointer.
400 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
401 StoreRefsForMemset[Ptr].push_back(SI);
402 } else if (ForMemsetPattern) {
403 // Find the base pointer.
404 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
405 StoreRefsForMemsetPattern[Ptr].push_back(SI);
406 } else if (ForMemcpy)
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000407 StoreRefsForMemcpy.push_back(SI);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000408 }
409}
410
Chris Lattner8455b6e2011-01-02 19:01:03 +0000411/// runOnLoopBlock - Process the specified block, which lives in a counted loop
412/// with the specified backedge count. This block is known to be in the current
413/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000414bool LoopIdiomRecognize::runOnLoopBlock(
415 BasicBlock *BB, const SCEV *BECount,
416 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000417 // We can only promote stores in this block if they are unconditionally
418 // executed in the loop. For a block to be unconditionally executed, it has
419 // to dominate all the exit blocks of the loop. Verify this now.
420 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
421 if (!DT->dominates(BB, ExitBlocks[i]))
422 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000423
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000424 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000425 // Look for store instructions, which may be optimized to memset/memcpy.
426 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000427
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000428 // Look for a single store or sets of stores with a common base, which can be
429 // optimized into a memset (memset_pattern). The latter most commonly happens
430 // with structs and handunrolled loops.
431 for (auto &SL : StoreRefsForMemset)
432 MadeChange |= processLoopStores(SL.second, BECount, true);
433
434 for (auto &SL : StoreRefsForMemsetPattern)
435 MadeChange |= processLoopStores(SL.second, BECount, false);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000436
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000437 // Optimize the store into a memcpy, if it feeds an similarly strided load.
438 for (auto &SI : StoreRefsForMemcpy)
439 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
440
Chandler Carruthbad690e2015-08-12 23:06:37 +0000441 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000442 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000443 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000444 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000445 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000446 if (!processLoopMemSet(MSI, BECount))
447 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000448 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000449
Chris Lattner86438102011-01-04 07:46:33 +0000450 // If processing the memset invalidated our iterator, start over from the
451 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000452 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000453 I = BB->begin();
454 continue;
455 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000456 }
Andrew Trick328b2232011-03-14 16:48:10 +0000457
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000458 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000459}
460
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000461/// processLoopStores - See if this store(s) can be promoted to a memset.
462bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
463 const SCEV *BECount,
464 bool ForMemset) {
465 // Try to find consecutive stores that can be transformed into memsets.
466 SetVector<StoreInst *> Heads, Tails;
467 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000468
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000469 // Do a quadratic search on all of the given stores and find
470 // all of the pairs of stores that follow each other.
471 SmallVector<unsigned, 16> IndexQueue;
472 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
473 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000474
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000475 Value *FirstStoredVal = SL[i]->getValueOperand();
476 Value *FirstStorePtr = SL[i]->getPointerOperand();
477 const SCEVAddRecExpr *FirstStoreEv =
478 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000479 APInt FirstStride = getStoreStride(FirstStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000480 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
Chad Rosier79676142015-10-28 14:38:49 +0000481
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000482 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000483 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000484 Heads.insert(SL[i]);
485 continue;
486 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000487
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000488 Value *FirstSplatValue = nullptr;
489 Constant *FirstPatternValue = nullptr;
490
491 if (ForMemset)
492 FirstSplatValue = isBytewiseValue(FirstStoredVal);
493 else
494 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
495
496 assert((FirstSplatValue || FirstPatternValue) &&
497 "Expected either splat value or pattern value.");
498
499 IndexQueue.clear();
500 // If a store has multiple consecutive store candidates, search Stores
501 // array according to the sequence: from i+1 to e, then from i-1 to 0.
502 // This is because usually pairing with immediate succeeding or preceding
503 // candidate create the best chance to find memset opportunity.
504 unsigned j = 0;
505 for (j = i + 1; j < e; ++j)
506 IndexQueue.push_back(j);
507 for (j = i; j > 0; --j)
508 IndexQueue.push_back(j - 1);
509
510 for (auto &k : IndexQueue) {
511 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
512 Value *SecondStorePtr = SL[k]->getPointerOperand();
513 const SCEVAddRecExpr *SecondStoreEv =
514 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000515 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000516
517 if (FirstStride != SecondStride)
518 continue;
519
520 Value *SecondStoredVal = SL[k]->getValueOperand();
521 Value *SecondSplatValue = nullptr;
522 Constant *SecondPatternValue = nullptr;
523
524 if (ForMemset)
525 SecondSplatValue = isBytewiseValue(SecondStoredVal);
526 else
527 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
528
529 assert((SecondSplatValue || SecondPatternValue) &&
530 "Expected either splat value or pattern value.");
531
532 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
533 if (ForMemset) {
534 if (FirstSplatValue != SecondSplatValue)
535 continue;
536 } else {
537 if (FirstPatternValue != SecondPatternValue)
538 continue;
539 }
540 Tails.insert(SL[k]);
541 Heads.insert(SL[i]);
542 ConsecutiveChain[SL[i]] = SL[k];
543 break;
544 }
545 }
546 }
547
548 // We may run into multiple chains that merge into a single chain. We mark the
549 // stores that we transformed so that we don't visit the same store twice.
550 SmallPtrSet<Value *, 16> TransformedStores;
551 bool Changed = false;
552
553 // For stores that start but don't end a link in the chain:
554 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
555 it != e; ++it) {
556 if (Tails.count(*it))
557 continue;
558
559 // We found a store instr that starts a chain. Now follow the chain and try
560 // to transform it.
561 SmallPtrSet<Instruction *, 8> AdjacentStores;
562 StoreInst *I = *it;
563
564 StoreInst *HeadStore = I;
565 unsigned StoreSize = 0;
566
567 // Collect the chain into a list.
568 while (Tails.count(I) || Heads.count(I)) {
569 if (TransformedStores.count(I))
570 break;
571 AdjacentStores.insert(I);
572
573 StoreSize += getStoreSizeInBytes(I, DL);
574 // Move to the next value in the chain.
575 I = ConsecutiveChain[I];
576 }
577
578 Value *StoredVal = HeadStore->getValueOperand();
579 Value *StorePtr = HeadStore->getPointerOperand();
580 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000581 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000582
583 // Check to see if the stride matches the size of the stores. If so, then
584 // we know that every byte is touched in the loop.
585 if (StoreSize != Stride && StoreSize != -Stride)
586 continue;
587
588 bool NegStride = StoreSize == -Stride;
589
590 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
591 StoredVal, HeadStore, AdjacentStores, StoreEv,
592 BECount, NegStride)) {
593 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
594 Changed = true;
595 }
596 }
597
598 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000599}
600
Chris Lattner86438102011-01-04 07:46:33 +0000601/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000602bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
603 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000604 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000605 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
606 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000607
Chris Lattnere6b261f2011-02-18 22:22:15 +0000608 // If we're not allowed to hack on memset, we fail.
609 if (!TLI->has(LibFunc::memset))
610 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000611
Chris Lattner86438102011-01-04 07:46:33 +0000612 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000613
Chris Lattner86438102011-01-04 07:46:33 +0000614 // See if the pointer expression is an AddRec like {base,+,1} on the current
615 // loop, which indicates a strided store. If we have something else, it's a
616 // random store we can't handle.
617 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000618 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000619 return false;
620
621 // Reject memsets that are so large that they overflow an unsigned.
622 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
623 if ((SizeInBytes >> 32) != 0)
624 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000625
Chris Lattner86438102011-01-04 07:46:33 +0000626 // Check to see if the stride matches the size of the memset. If so, then we
627 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000628 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
629 if (!ConstStride)
630 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000631
Chad Rosier81362a82016-02-12 21:03:23 +0000632 APInt Stride = ConstStride->getAPInt();
633 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000634 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000635
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000636 // Verify that the memset value is loop invariant. If not, we can't promote
637 // the memset.
638 Value *SplatValue = MSI->getValue();
639 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
640 return false;
641
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000642 SmallPtrSet<Instruction *, 1> MSIs;
643 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000644 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000645 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000646 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
Chad Rosier81362a82016-02-12 21:03:23 +0000647 BECount, NegStride);
Chris Lattner86438102011-01-04 07:46:33 +0000648}
649
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000650/// mayLoopAccessLocation - Return true if the specified loop might access the
651/// specified pointer location, which is a loop-strided access. The 'Access'
652/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000653static bool
654mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
655 const SCEV *BECount, unsigned StoreSize,
656 AliasAnalysis &AA,
657 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000658 // Get the location that may be stored across the loop. Since the access is
659 // strided positively through memory, we say that the modified location starts
660 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000661 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000662
663 // If the loop iterates a fixed number of times, we can refine the access size
664 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
665 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000666 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000667
668 // TODO: For this to be really effective, we have to dive into the pointer
669 // operand in the store. Store to &A[i] of 100 will always return may alias
670 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
671 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000672 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000673
674 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
675 ++BI)
676 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000677 if (IgnoredStores.count(&*I) == 0 &&
678 (AA.getModRefInfo(&*I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000679 return true;
680
681 return false;
682}
683
Chad Rosiered0c7d12015-11-13 19:11:07 +0000684// If we have a negative stride, Start refers to the end of the memory location
685// we're trying to memset. Therefore, we need to recompute the base pointer,
686// which is just Start - BECount*Size.
687static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
688 Type *IntPtr, unsigned StoreSize,
689 ScalarEvolution *SE) {
690 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
691 if (StoreSize != 1)
692 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
693 SCEV::FlagNUW);
694 return SE->getMinusSCEV(Start, Index);
695}
696
Chris Lattner0f4a6402011-02-19 19:31:39 +0000697/// processLoopStridedStore - We see a strided store of some value. If we can
698/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000699bool LoopIdiomRecognize::processLoopStridedStore(
700 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000701 Value *StoredVal, Instruction *TheStore,
702 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000703 const SCEV *BECount, bool NegStride) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000704 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000705 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000706
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000707 if (!SplatValue)
708 PatternValue = getMemSetPatternValue(StoredVal, DL);
709
710 assert((SplatValue || PatternValue) &&
711 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000712
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000713 // The trip count of the loop and the base pointer of the addrec SCEV is
714 // guaranteed to be loop invariant, which means that it should dominate the
715 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000716 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000717 BasicBlock *Preheader = CurLoop->getLoopPreheader();
718 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000719 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000720
Matt Arsenault009faed2013-09-11 05:09:42 +0000721 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000722 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000723
724 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000725 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000726 if (NegStride)
727 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000728
Chris Lattner29e14ed2010-12-26 23:42:51 +0000729 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000730 // this into a memset in the loop preheader now if we want. However, this
731 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000732 // or write to the aliased location. Check for any overlap by generating the
733 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000734 Value *BasePtr =
735 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000736 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000737 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000738 Expander.clear();
739 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000740 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000741 return false;
742 }
743
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000744 // Okay, everything looks good, insert the memset.
745
Chris Lattner29e14ed2010-12-26 23:42:51 +0000746 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
747 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000748 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000749
Chandler Carruthbad690e2015-08-12 23:06:37 +0000750 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000751 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000752 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000753 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000754 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000755 }
Andrew Trick328b2232011-03-14 16:48:10 +0000756
757 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000758 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000759
Devang Pateld00c6282011-03-07 22:43:45 +0000760 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000761 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000762 NewCall =
763 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000764 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000765 // Everything is emitted in default address space
766 Type *Int8PtrTy = DestInt8PtrTy;
767
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000768 Module *M = TheStore->getModule();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000769 Value *MSP =
770 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
771 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000772
Chris Lattner0f4a6402011-02-19 19:31:39 +0000773 // Otherwise we should form a memset_pattern16. PatternValue is known to be
774 // an constant array of 16-bytes. Plop the value into a mergable global.
775 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000776 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000777 PatternValue, ".memset_pattern");
778 GV->setUnnamedAddr(true); // Ok to merge these.
779 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000780 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000781 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000782 }
Andrew Trick328b2232011-03-14 16:48:10 +0000783
Chris Lattner29e14ed2010-12-26 23:42:51 +0000784 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000785 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000786 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000787
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000788 // Okay, the memset has been formed. Zap the original store and anything that
789 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000790 for (auto *I : Stores)
791 deleteDeadInstruction(I, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000792 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000793 return true;
794}
795
Chad Rosier1cd3da12015-11-19 21:33:07 +0000796/// If the stored value is a strided load in the same loop with the same stride
797/// this may be transformable into a memcpy. This kicks in for stuff like
798/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000799bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
800 const SCEV *BECount) {
801 assert(SI->isSimple() && "Expected only non-volatile stores.");
802
803 Value *StorePtr = SI->getPointerOperand();
804 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000805 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000806 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
807 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000808
Chad Rosierfddc01f2015-11-19 18:22:21 +0000809 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000810 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
811 assert(LI->isSimple() && "Expected only non-volatile stores.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000812
813 // See if the pointer expression is an AddRec like {base,+,1} on the current
814 // loop, which indicates a strided load. If we have something else, it's a
815 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000816 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000817 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000818
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000819 // The trip count of the loop and the base pointer of the addrec SCEV is
820 // guaranteed to be loop invariant, which means that it should dominate the
821 // header. This allows us to insert code for it in the preheader.
822 BasicBlock *Preheader = CurLoop->getLoopPreheader();
823 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000824 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000825
Chad Rosiercc299b62015-11-13 21:51:02 +0000826 const SCEV *StrStart = StoreEv->getStart();
827 unsigned StrAS = SI->getPointerAddressSpace();
828 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
829
830 // Handle negative strided loops.
831 if (NegStride)
832 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
833
Chris Lattner85b6d812011-01-02 03:37:56 +0000834 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000835 // this into a memcpy in the loop preheader now if we want. However, this
836 // would be unsafe to do if there is anything else in the loop that may read
837 // or write the memory region we're storing to. This includes the load that
838 // feeds the stores. Check for an alias by generating the base address and
839 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000840 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000841 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000842
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000843 SmallPtrSet<Instruction *, 1> Stores;
844 Stores.insert(SI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000845 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000846 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000847 Expander.clear();
848 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000849 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000850 return false;
851 }
852
Chad Rosiercc299b62015-11-13 21:51:02 +0000853 const SCEV *LdStart = LoadEv->getStart();
854 unsigned LdAS = LI->getPointerAddressSpace();
855
856 // Handle negative strided loops.
857 if (NegStride)
858 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
859
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000860 // For a memcpy, we have to make sure that the input array is not being
861 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000862 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000863 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000864
Chandler Carruth194f59c2015-07-22 23:15:57 +0000865 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000866 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000867 Expander.clear();
868 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000869 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
870 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000871 return false;
872 }
873
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000874 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000875
Chris Lattner85b6d812011-01-02 03:37:56 +0000876 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
877 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +0000878 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000879
Chandler Carruthbad690e2015-08-12 23:06:37 +0000880 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000881 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000882 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000883 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000884 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000885
Chris Lattner85b6d812011-01-02 03:37:56 +0000886 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000887 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000888
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000889 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000890 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000891 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000892 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000893
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000894 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000895 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
896 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000897
Chad Rosier7f08d802015-10-13 20:59:16 +0000898 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000899 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000900 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000901 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000902 return true;
903}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000904
905bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chad Rosier19dc92d2015-11-09 16:56:06 +0000906 return recognizePopcount();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000907}
Chandler Carruth8219a502015-08-13 00:44:29 +0000908
909/// Check if the given conditional branch is based on the comparison between
910/// a variable and zero, and if the variable is non-zero, the control yields to
911/// the loop entry. If the branch matches the behavior, the variable involved
912/// in the comparion is returned. This function will be called to see if the
913/// precondition and postcondition of the loop are in desirable form.
914static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
915 if (!BI || !BI->isConditional())
916 return nullptr;
917
918 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
919 if (!Cond)
920 return nullptr;
921
922 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
923 if (!CmpZero || !CmpZero->isZero())
924 return nullptr;
925
926 ICmpInst::Predicate Pred = Cond->getPredicate();
927 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
928 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
929 return Cond->getOperand(0);
930
931 return nullptr;
932}
933
934/// Return true iff the idiom is detected in the loop.
935///
936/// Additionally:
937/// 1) \p CntInst is set to the instruction counting the population bit.
938/// 2) \p CntPhi is set to the corresponding phi node.
939/// 3) \p Var is set to the value whose population bits are being counted.
940///
941/// The core idiom we are trying to detect is:
942/// \code
943/// if (x0 != 0)
944/// goto loop-exit // the precondition of the loop
945/// cnt0 = init-val;
946/// do {
947/// x1 = phi (x0, x2);
948/// cnt1 = phi(cnt0, cnt2);
949///
950/// cnt2 = cnt1 + 1;
951/// ...
952/// x2 = x1 & (x1 - 1);
953/// ...
954/// } while(x != 0);
955///
956/// loop-exit:
957/// \endcode
958static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
959 Instruction *&CntInst, PHINode *&CntPhi,
960 Value *&Var) {
961 // step 1: Check to see if the look-back branch match this pattern:
962 // "if (a!=0) goto loop-entry".
963 BasicBlock *LoopEntry;
964 Instruction *DefX2, *CountInst;
965 Value *VarX1, *VarX0;
966 PHINode *PhiX, *CountPhi;
967
968 DefX2 = CountInst = nullptr;
969 VarX1 = VarX0 = nullptr;
970 PhiX = CountPhi = nullptr;
971 LoopEntry = *(CurLoop->block_begin());
972
973 // step 1: Check if the loop-back branch is in desirable form.
974 {
975 if (Value *T = matchCondition(
976 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
977 DefX2 = dyn_cast<Instruction>(T);
978 else
979 return false;
980 }
981
982 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
983 {
984 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
985 return false;
986
987 BinaryOperator *SubOneOp;
988
989 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
990 VarX1 = DefX2->getOperand(1);
991 else {
992 VarX1 = DefX2->getOperand(0);
993 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
994 }
995 if (!SubOneOp)
996 return false;
997
998 Instruction *SubInst = cast<Instruction>(SubOneOp);
999 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1000 if (!Dec ||
1001 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1002 (SubInst->getOpcode() == Instruction::Add &&
1003 Dec->isAllOnesValue()))) {
1004 return false;
1005 }
1006 }
1007
1008 // step 3: Check the recurrence of variable X
1009 {
1010 PhiX = dyn_cast<PHINode>(VarX1);
1011 if (!PhiX ||
1012 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
1013 return false;
1014 }
1015 }
1016
1017 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1018 {
1019 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001020 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001021 IterE = LoopEntry->end();
1022 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001023 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001024 if (Inst->getOpcode() != Instruction::Add)
1025 continue;
1026
1027 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1028 if (!Inc || !Inc->isOne())
1029 continue;
1030
1031 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
1032 if (!Phi || Phi->getParent() != LoopEntry)
1033 continue;
1034
1035 // Check if the result of the instruction is live of the loop.
1036 bool LiveOutLoop = false;
1037 for (User *U : Inst->users()) {
1038 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1039 LiveOutLoop = true;
1040 break;
1041 }
1042 }
1043
1044 if (LiveOutLoop) {
1045 CountInst = Inst;
1046 CountPhi = Phi;
1047 break;
1048 }
1049 }
1050
1051 if (!CountInst)
1052 return false;
1053 }
1054
1055 // step 5: check if the precondition is in this form:
1056 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1057 {
1058 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1059 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1060 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1061 return false;
1062
1063 CntInst = CountInst;
1064 CntPhi = CountPhi;
1065 Var = T;
1066 }
1067
1068 return true;
1069}
1070
1071/// Recognizes a population count idiom in a non-countable loop.
1072///
1073/// If detected, transforms the relevant code to issue the popcount intrinsic
1074/// function call, and returns true; otherwise, returns false.
1075bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001076 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1077 return false;
1078
1079 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001080 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001081 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1082 // in a compact loop.
1083
Renato Golin655348f2015-08-13 11:25:38 +00001084 // Give up if the loop has multiple blocks or multiple backedges.
1085 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001086 return false;
1087
Renato Golin655348f2015-08-13 11:25:38 +00001088 BasicBlock *LoopBody = *(CurLoop->block_begin());
1089 if (LoopBody->size() >= 20) {
1090 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001091 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001092 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001093
1094 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001095 BasicBlock *PH = CurLoop->getLoopPreheader();
1096 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +00001097 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001098 if (&PH->front() != PH->getTerminator())
1099 return false;
1100 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001101 if (!EntryBI || EntryBI->isConditional())
1102 return false;
1103
1104 // It should have a precondition block where the generated popcount instrinsic
1105 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001106 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001107 if (!PreCondBB)
1108 return false;
1109 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1110 if (!PreCondBI || PreCondBI->isUnconditional())
1111 return false;
1112
1113 Instruction *CntInst;
1114 PHINode *CntPhi;
1115 Value *Val;
1116 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1117 return false;
1118
1119 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1120 return true;
1121}
1122
1123static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1124 DebugLoc DL) {
1125 Value *Ops[] = {Val};
1126 Type *Tys[] = {Val->getType()};
1127
1128 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1129 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1130 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1131 CI->setDebugLoc(DL);
1132
1133 return CI;
1134}
1135
1136void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1137 Instruction *CntInst,
1138 PHINode *CntPhi, Value *Var) {
1139 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1140 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1141 const DebugLoc DL = CntInst->getDebugLoc();
1142
1143 // Assuming before transformation, the loop is following:
1144 // if (x) // the precondition
1145 // do { cnt++; x &= x - 1; } while(x);
1146
1147 // Step 1: Insert the ctpop instruction at the end of the precondition block
1148 IRBuilder<> Builder(PreCondBr);
1149 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1150 {
1151 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1152 NewCount = PopCntZext =
1153 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1154
1155 if (NewCount != PopCnt)
1156 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1157
1158 // TripCnt is exactly the number of iterations the loop has
1159 TripCnt = NewCount;
1160
1161 // If the population counter's initial value is not zero, insert Add Inst.
1162 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1163 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1164 if (!InitConst || !InitConst->isZero()) {
1165 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1166 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1167 }
1168 }
1169
Nick Lewycky2c852542015-08-19 06:22:33 +00001170 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001171 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001172 // function would be partial dead code, and downstream passes will drag
1173 // it back from the precondition block to the preheader.
1174 {
1175 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1176
1177 Value *Opnd0 = PopCntZext;
1178 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1179 if (PreCond->getOperand(0) != Var)
1180 std::swap(Opnd0, Opnd1);
1181
1182 ICmpInst *NewPreCond = cast<ICmpInst>(
1183 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1184 PreCondBr->setCondition(NewPreCond);
1185
1186 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1187 }
1188
1189 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001190 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001191 // loop into a countable one. The benefit is twofold:
1192 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001193 // - If the loop only counts population, the entire loop becomes dead after
1194 // the transformation. It is a lot easier to prove a countable loop dead
1195 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001196 // isn't dead even if it computes nothing useful. In general, DCE needs
1197 // to prove a noncountable loop finite before safely delete it.)
1198 //
1199 // - If the loop also performs something else, it remains alive.
1200 // Since it is transformed to countable form, it can be aggressively
1201 // optimized by some optimizations which are in general not applicable
1202 // to a noncountable loop.
1203 //
1204 // After this step, this loop (conceptually) would look like following:
1205 // newcnt = __builtin_ctpop(x);
1206 // t = newcnt;
1207 // if (x)
1208 // do { cnt++; x &= x-1; t--) } while (t > 0);
1209 BasicBlock *Body = *(CurLoop->block_begin());
1210 {
1211 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1212 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1213 Type *Ty = TripCnt->getType();
1214
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001215 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001216
1217 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001218 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001219 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1220 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001221
1222 TcPhi->addIncoming(TripCnt, PreHead);
1223 TcPhi->addIncoming(TcDec, Body);
1224
1225 CmpInst::Predicate Pred =
1226 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1227 LbCond->setPredicate(Pred);
1228 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001229 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001230 }
1231
1232 // Step 4: All the references to the original population counter outside
1233 // the loop are replaced with the NewCount -- the value returned from
1234 // __builtin_ctpop().
1235 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1236
1237 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1238 // loop. The loop would otherwise not be deleted even if it becomes empty.
1239 SE->forgetLoop(CurLoop);
1240}