blob: 9051b7ceb3a7e917bbe61b6766a1a2176830719c [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//
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000014// If compiling for code size we avoid idiom recognition if the resulting
15// code could be larger than the code for the original loop. One way this could
16// happen is if the loop is not removable after idiom recognition due to the
17// presence of non-idiom instructions. The initial implementation of the
18// heuristics applies to idioms in multi-block loops.
19//
Chris Lattner81ae3f22010-12-26 19:39:38 +000020//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000021//
22// TODO List:
23//
24// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000025// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000026// Future floating point idioms to recognize in -ffast-math mode:
27// fpowi
28// Future integer operation idioms to recognize:
29// ctpop, ctlz, cttz
30//
31// Beware that isel's default lowering for ctpop is highly inefficient for
32// i64 and larger types when i64 is legal and the value has few bits set. It
33// would be good to enhance isel to emit a loop for ctpop in this case.
34//
Chris Lattner02a97762011-01-03 01:10:08 +000035// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000036// replace them with calls to BLAS (if linked in??).
37//
Chris Lattner0469e012011-01-02 18:32:09 +000038//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000039
Dehao Chenb9f8e292016-07-12 18:45:51 +000040#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000041#include "llvm/ADT/MapVector.h"
42#include "llvm/ADT/SetVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000044#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000045#include "llvm/Analysis/BasicAliasAnalysis.h"
46#include "llvm/Analysis/GlobalsModRef.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000047#include "llvm/Analysis/LoopAccessAnalysis.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000048#include "llvm/Analysis/LoopPass.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000050#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000054#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/IntrinsicInst.h"
59#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000060#include "llvm/Support/Debug.h"
61#include "llvm/Support/raw_ostream.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000062#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000063#include "llvm/Transforms/Scalar/LoopPassManager.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000064#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000065#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000066#include "llvm/Transforms/Utils/LoopUtils.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000067using namespace llvm;
68
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "loop-idiom"
70
Chandler Carruth099f5cb02012-11-02 08:33:25 +000071STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
72STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000073
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000074static cl::opt<bool> UseLIRCodeSizeHeurs(
75 "use-lir-code-size-heurs",
76 cl::desc("Use loop idiom recognition code size heuristics when compiling"
77 "with -Os/-Oz"),
78 cl::init(true), cl::Hidden);
79
Chris Lattner81ae3f22010-12-26 19:39:38 +000080namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000081
Dehao Chenb9f8e292016-07-12 18:45:51 +000082class LoopIdiomRecognize {
Chandler Carruthbad690e2015-08-12 23:06:37 +000083 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000084 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000085 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000086 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000087 ScalarEvolution *SE;
88 TargetLibraryInfo *TLI;
89 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +000090 const DataLayout *DL;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000091 bool ApplyCodeSizeHeuristics;
Chris Lattner81ae3f22010-12-26 19:39:38 +000092
Chandler Carruthbad690e2015-08-12 23:06:37 +000093public:
Dehao Chenb9f8e292016-07-12 18:45:51 +000094 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
95 LoopInfo *LI, ScalarEvolution *SE,
96 TargetLibraryInfo *TLI,
97 const TargetTransformInfo *TTI,
98 const DataLayout *DL)
99 : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
100 DL(DL) {}
Chris Lattner81ae3f22010-12-26 19:39:38 +0000101
Dehao Chenb9f8e292016-07-12 18:45:51 +0000102 bool runOnLoop(Loop *L);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000103
Chandler Carruthbad690e2015-08-12 23:06:37 +0000104private:
Chad Rosiercc9030b2015-11-11 23:00:59 +0000105 typedef SmallVector<StoreInst *, 8> StoreList;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000106 typedef MapVector<Value *, StoreList> StoreListMap;
107 StoreListMap StoreRefsForMemset;
108 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000109 StoreList StoreRefsForMemcpy;
110 bool HasMemset;
111 bool HasMemsetPattern;
112 bool HasMemcpy;
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000113 /// Return code for isLegalStore()
114 enum LegalStoreKind {
Anna Thomasae3f752f2017-05-19 18:00:30 +0000115 None = 0,
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000116 Memset,
117 MemsetPattern,
118 Memcpy,
Anna Thomasb2a212c2017-06-06 16:45:25 +0000119 UnorderedAtomicMemcpy,
Anna Thomasae3f752f2017-05-19 18:00:30 +0000120 DontUse // Dummy retval never to be used. Allows catching errors in retval
121 // handling.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000122 };
Chad Rosiercc9030b2015-11-11 23:00:59 +0000123
Chandler Carruthd9c60702015-08-13 00:10:03 +0000124 /// \name Countable Loop Idiom Handling
125 /// @{
126
Chandler Carruthbad690e2015-08-12 23:06:37 +0000127 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000128 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
129 SmallVectorImpl<BasicBlock *> &ExitBlocks);
130
Chad Rosiercc9030b2015-11-11 23:00:59 +0000131 void collectStores(BasicBlock *BB);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000132 LegalStoreKind isLegalStore(StoreInst *SI);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000133 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
134 bool ForMemset);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000135 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
136
137 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000138 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000139 Instruction *TheStore,
140 SmallPtrSetImpl<Instruction *> &Stores,
141 const SCEVAddRecExpr *Ev, const SCEV *BECount,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000142 bool NegStride, bool IsLoopMemset = false);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000143 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000144 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
145 bool IsLoopMemset = false);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000146
147 /// @}
148 /// \name Noncountable Loop Idiom Handling
149 /// @{
150
151 bool runOnNoncountableLoop();
152
Chandler Carruth8219a502015-08-13 00:44:29 +0000153 bool recognizePopcount();
154 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
155 PHINode *CntPhi, Value *Var);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +0000156 bool recognizeAndInsertCTLZ();
157 void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst,
158 PHINode *CntPhi, Value *Var, const DebugLoc DL,
159 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop);
Chandler Carruth8219a502015-08-13 00:44:29 +0000160
Chandler Carruthd9c60702015-08-13 00:10:03 +0000161 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000162};
163
Dehao Chenb9f8e292016-07-12 18:45:51 +0000164class LoopIdiomRecognizeLegacyPass : public LoopPass {
165public:
166 static char ID;
167 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
168 initializeLoopIdiomRecognizeLegacyPassPass(
169 *PassRegistry::getPassRegistry());
170 }
171
172 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
173 if (skipLoop(L))
174 return false;
175
176 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
177 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
178 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
179 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
180 TargetLibraryInfo *TLI =
181 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
182 const TargetTransformInfo *TTI =
183 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
184 *L->getHeader()->getParent());
185 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
186
187 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
188 return LIR.runOnLoop(L);
189 }
190
191 /// This transformation requires natural loop information & requires that
192 /// loop preheaders be inserted into the CFG.
193 ///
194 void getAnalysisUsage(AnalysisUsage &AU) const override {
195 AU.addRequired<TargetLibraryInfoWrapperPass>();
196 AU.addRequired<TargetTransformInfoWrapperPass>();
197 getLoopAnalysisUsage(AU);
198 }
199};
Chandler Carruthbad690e2015-08-12 23:06:37 +0000200} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000201
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000202PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
203 LoopStandardAnalysisResults &AR,
204 LPMUpdater &) {
Dehao Chenb9f8e292016-07-12 18:45:51 +0000205 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
Dehao Chenb9f8e292016-07-12 18:45:51 +0000206
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000207 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000208 if (!LIR.runOnLoop(&L))
209 return PreservedAnalyses::all();
210
211 return getLoopPassPreservedAnalyses();
212}
213
214char LoopIdiomRecognizeLegacyPass::ID = 0;
215INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
216 "Recognize loop idioms", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000217INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000218INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000219INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Dehao Chenb9f8e292016-07-12 18:45:51 +0000220INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
221 "Recognize loop idioms", false, false)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000222
Dehao Chenb9f8e292016-07-12 18:45:51 +0000223Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000224
David Majnemerc5601df2016-06-20 16:03:25 +0000225static void deleteDeadInstruction(Instruction *I) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000226 I->replaceAllUsesWith(UndefValue::get(I->getType()));
227 I->eraseFromParent();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000228}
229
Shuxin Yang95de7c32012-12-09 03:12:46 +0000230//===----------------------------------------------------------------------===//
231//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000232// Implementation of LoopIdiomRecognize
233//
234//===----------------------------------------------------------------------===//
235
Dehao Chenb9f8e292016-07-12 18:45:51 +0000236bool LoopIdiomRecognize::runOnLoop(Loop *L) {
Chandler Carruthd9c60702015-08-13 00:10:03 +0000237 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000238 // If the loop could not be converted to canonical form, it must have an
239 // indirectbr in it, just give up.
240 if (!L->getLoopPreheader())
241 return false;
242
243 // Disable loop idiom recognition if the function's name is a common idiom.
244 StringRef Name = L->getHeader()->getParent()->getName();
245 if (Name == "memset" || Name == "memcpy")
246 return false;
247
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000248 // Determine if code size heuristics need to be applied.
249 ApplyCodeSizeHeuristics =
250 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
251
David L. Jonesd21529f2017-01-23 23:16:46 +0000252 HasMemset = TLI->has(LibFunc_memset);
253 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
254 HasMemcpy = TLI->has(LibFunc_memcpy);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000255
256 if (HasMemset || HasMemsetPattern || HasMemcpy)
257 if (SE->hasLoopInvariantBackedgeTakenCount(L))
258 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000259
Chandler Carruthd9c60702015-08-13 00:10:03 +0000260 return runOnNoncountableLoop();
261}
262
Shuxin Yang95de7c32012-12-09 03:12:46 +0000263bool LoopIdiomRecognize::runOnCountableLoop() {
264 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000265 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000266 "runOnCountableLoop() called on a loop without a predictable"
267 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000268
269 // If this loop executes exactly one time, then it should be peeled, not
270 // optimized by this pass.
271 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000272 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000273 return false;
274
Chandler Carruthbad690e2015-08-12 23:06:37 +0000275 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000276 CurLoop->getUniqueExitBlocks(ExitBlocks);
277
278 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000279 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
280 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000281
282 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000283
284 // The following transforms hoist stores/memsets into the loop pre-header.
285 // Give up if the loop has instructions may throw.
286 LoopSafetyInfo SafetyInfo;
287 computeLoopSafetyInfo(&SafetyInfo, CurLoop);
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000288 if (SafetyInfo.MayThrow)
Haicheng Wua95cd1262016-07-06 21:05:40 +0000289 return MadeChange;
290
Shuxin Yang95de7c32012-12-09 03:12:46 +0000291 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000292 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000293 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000294 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000295 continue;
296
Davide Italiano80625af2015-05-13 19:51:21 +0000297 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000298 }
299 return MadeChange;
300}
301
Chad Rosiera548fe52015-11-12 19:09:16 +0000302static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
303 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
304 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
305 "Don't overflow unsigned.");
306 return (unsigned)SizeInBits >> 3;
307}
308
Chad Rosier4acff962016-02-12 19:05:27 +0000309static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000310 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000311 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000312}
313
Chad Rosier94274fb2015-12-21 14:49:32 +0000314/// getMemSetPatternValue - If a strided store of the specified value is safe to
315/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
316/// be passed in. Otherwise, return null.
317///
318/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
319/// just replicate their input array and then pass on to memset_pattern16.
320static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
321 // If the value isn't a constant, we can't promote it to being in a constant
322 // array. We could theoretically do a store to an alloca or something, but
323 // that doesn't seem worthwhile.
324 Constant *C = dyn_cast<Constant>(V);
325 if (!C)
326 return nullptr;
327
328 // Only handle simple values that are a power of two bytes in size.
329 uint64_t Size = DL->getTypeSizeInBits(V->getType());
330 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
331 return nullptr;
332
333 // Don't care enough about darwin/ppc to implement this.
334 if (DL->isBigEndian())
335 return nullptr;
336
337 // Convert to size in bytes.
338 Size /= 8;
339
340 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
341 // if the top and bottom are the same (e.g. for vectors and large integers).
342 if (Size > 16)
343 return nullptr;
344
345 // If the constant is exactly 16 bytes, just use it.
346 if (Size == 16)
347 return C;
348
349 // Otherwise, we'll use an array of the constants.
350 unsigned ArraySize = 16 / Size;
351 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
352 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
353}
354
Anna Thomasae3f752f2017-05-19 18:00:30 +0000355LoopIdiomRecognize::LegalStoreKind
356LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000357
Chad Rosier869962f2015-12-01 14:26:35 +0000358 // Don't touch volatile stores.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000359 if (SI->isVolatile())
360 return LegalStoreKind::None;
361 // We only want simple or unordered-atomic stores.
362 if (!SI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000363 return LegalStoreKind::None;
Chad Rosier869962f2015-12-01 14:26:35 +0000364
Sanjoy Das206f65c2017-04-24 20:12:10 +0000365 // Don't convert stores of non-integral pointer types to memsets (which stores
366 // integers).
367 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000368 return LegalStoreKind::None;
Sanjoy Das206f65c2017-04-24 20:12:10 +0000369
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000370 // Avoid merging nontemporal stores.
371 if (SI->getMetadata(LLVMContext::MD_nontemporal))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000372 return LegalStoreKind::None;
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000373
Chad Rosiera548fe52015-11-12 19:09:16 +0000374 Value *StoredVal = SI->getValueOperand();
375 Value *StorePtr = SI->getPointerOperand();
376
377 // Reject stores that are so large that they overflow an unsigned.
378 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
379 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000380 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000381
382 // See if the pointer expression is an AddRec like {base,+,1} on the current
383 // loop, which indicates a strided store. If we have something else, it's a
384 // random store we can't handle.
385 const SCEVAddRecExpr *StoreEv =
386 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
387 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000388 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000389
390 // Check to see if we have a constant stride.
391 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000392 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000393
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000394 // See if the store can be turned into a memset.
395
396 // If the stored value is a byte-wise value (like i32 -1), then it may be
397 // turned into a memset of i8 -1, assuming that all the consecutive bytes
398 // are stored. A store of i32 0x01020304 can never be turned into a memset,
399 // but it can be turned into memset_pattern if the target supports it.
400 Value *SplatValue = isBytewiseValue(StoredVal);
401 Constant *PatternValue = nullptr;
402
Anna Thomasb2a212c2017-06-06 16:45:25 +0000403 // Note: memset and memset_pattern on unordered-atomic is yet not supported
404 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
405
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000406 // If we're allowed to form a memset, and the stored value would be
407 // acceptable for memset, use it.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000408 if (!UnorderedAtomic && HasMemset && SplatValue &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000409 // Verify that the stored value is loop invariant. If not, we can't
410 // promote the memset.
411 CurLoop->isLoopInvariant(SplatValue)) {
412 // It looks like we can use SplatValue.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000413 return LegalStoreKind::Memset;
Anna Thomasb2a212c2017-06-06 16:45:25 +0000414 } else if (!UnorderedAtomic && HasMemsetPattern &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000415 // Don't create memset_pattern16s with address spaces.
416 StorePtr->getType()->getPointerAddressSpace() == 0 &&
417 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
418 // It looks like we can use PatternValue!
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000419 return LegalStoreKind::MemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000420 }
421
422 // Otherwise, see if the store can be turned into a memcpy.
423 if (HasMemcpy) {
424 // Check to see if the stride matches the size of the store. If so, then we
425 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000426 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000427 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
428 if (StoreSize != Stride && StoreSize != -Stride)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000429 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000430
431 // The store must be feeding a non-volatile load.
432 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000433
434 // Only allow non-volatile loads
435 if (!LI || LI->isVolatile())
436 return LegalStoreKind::None;
437 // Only allow simple or unordered-atomic loads
438 if (!LI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000439 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000440
441 // See if the pointer expression is an AddRec like {base,+,1} on the current
442 // loop, which indicates a strided load. If we have something else, it's a
443 // random load we can't handle.
444 const SCEVAddRecExpr *LoadEv =
445 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
446 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000447 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000448
449 // The store and load must share the same stride.
450 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000451 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000452
453 // Success. This store can be converted into a memcpy.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000454 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
455 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
456 : LegalStoreKind::Memcpy;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000457 }
458 // This store can't be transformed into a memset/memcpy.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000459 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000460}
461
Chad Rosiercc9030b2015-11-11 23:00:59 +0000462void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000463 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000464 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000465 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000466 for (Instruction &I : *BB) {
467 StoreInst *SI = dyn_cast<StoreInst>(&I);
468 if (!SI)
469 continue;
470
Chad Rosiera548fe52015-11-12 19:09:16 +0000471 // Make sure this is a strided store with a constant stride.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000472 switch (isLegalStore(SI)) {
473 case LegalStoreKind::None:
474 // Nothing to do
475 break;
476 case LegalStoreKind::Memset: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000477 // Find the base pointer.
478 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
479 StoreRefsForMemset[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000480 } break;
481 case LegalStoreKind::MemsetPattern: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000482 // Find the base pointer.
483 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
484 StoreRefsForMemsetPattern[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000485 } break;
486 case LegalStoreKind::Memcpy:
Anna Thomasb2a212c2017-06-06 16:45:25 +0000487 case LegalStoreKind::UnorderedAtomicMemcpy:
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000488 StoreRefsForMemcpy.push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000489 break;
490 default:
491 assert(false && "unhandled return value");
492 break;
493 }
Chad Rosiercc9030b2015-11-11 23:00:59 +0000494 }
495}
496
Chris Lattner8455b6e2011-01-02 19:01:03 +0000497/// runOnLoopBlock - Process the specified block, which lives in a counted loop
498/// with the specified backedge count. This block is known to be in the current
499/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000500bool LoopIdiomRecognize::runOnLoopBlock(
501 BasicBlock *BB, const SCEV *BECount,
502 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000503 // We can only promote stores in this block if they are unconditionally
504 // executed in the loop. For a block to be unconditionally executed, it has
505 // to dominate all the exit blocks of the loop. Verify this now.
506 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
507 if (!DT->dominates(BB, ExitBlocks[i]))
508 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000509
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000510 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000511 // Look for store instructions, which may be optimized to memset/memcpy.
512 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000513
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000514 // Look for a single store or sets of stores with a common base, which can be
515 // optimized into a memset (memset_pattern). The latter most commonly happens
516 // with structs and handunrolled loops.
517 for (auto &SL : StoreRefsForMemset)
518 MadeChange |= processLoopStores(SL.second, BECount, true);
519
520 for (auto &SL : StoreRefsForMemsetPattern)
521 MadeChange |= processLoopStores(SL.second, BECount, false);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000522
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000523 // Optimize the store into a memcpy, if it feeds an similarly strided load.
524 for (auto &SI : StoreRefsForMemcpy)
525 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
526
Chandler Carruthbad690e2015-08-12 23:06:37 +0000527 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000528 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000529 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000530 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000531 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000532 if (!processLoopMemSet(MSI, BECount))
533 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000534 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000535
Chris Lattner86438102011-01-04 07:46:33 +0000536 // If processing the memset invalidated our iterator, start over from the
537 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000538 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000539 I = BB->begin();
540 continue;
541 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000542 }
Andrew Trick328b2232011-03-14 16:48:10 +0000543
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000544 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000545}
546
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000547/// processLoopStores - See if this store(s) can be promoted to a memset.
548bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
549 const SCEV *BECount,
550 bool ForMemset) {
551 // Try to find consecutive stores that can be transformed into memsets.
552 SetVector<StoreInst *> Heads, Tails;
553 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000554
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000555 // Do a quadratic search on all of the given stores and find
556 // all of the pairs of stores that follow each other.
557 SmallVector<unsigned, 16> IndexQueue;
558 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
559 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000560
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000561 Value *FirstStoredVal = SL[i]->getValueOperand();
562 Value *FirstStorePtr = SL[i]->getPointerOperand();
563 const SCEVAddRecExpr *FirstStoreEv =
564 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000565 APInt FirstStride = getStoreStride(FirstStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000566 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
Chad Rosier79676142015-10-28 14:38:49 +0000567
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000568 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000569 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000570 Heads.insert(SL[i]);
571 continue;
572 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000573
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000574 Value *FirstSplatValue = nullptr;
575 Constant *FirstPatternValue = nullptr;
576
577 if (ForMemset)
578 FirstSplatValue = isBytewiseValue(FirstStoredVal);
579 else
580 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
581
582 assert((FirstSplatValue || FirstPatternValue) &&
583 "Expected either splat value or pattern value.");
584
585 IndexQueue.clear();
586 // If a store has multiple consecutive store candidates, search Stores
587 // array according to the sequence: from i+1 to e, then from i-1 to 0.
588 // This is because usually pairing with immediate succeeding or preceding
589 // candidate create the best chance to find memset opportunity.
590 unsigned j = 0;
591 for (j = i + 1; j < e; ++j)
592 IndexQueue.push_back(j);
593 for (j = i; j > 0; --j)
594 IndexQueue.push_back(j - 1);
595
596 for (auto &k : IndexQueue) {
597 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
598 Value *SecondStorePtr = SL[k]->getPointerOperand();
599 const SCEVAddRecExpr *SecondStoreEv =
600 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000601 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000602
603 if (FirstStride != SecondStride)
604 continue;
605
606 Value *SecondStoredVal = SL[k]->getValueOperand();
607 Value *SecondSplatValue = nullptr;
608 Constant *SecondPatternValue = nullptr;
609
610 if (ForMemset)
611 SecondSplatValue = isBytewiseValue(SecondStoredVal);
612 else
613 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
614
615 assert((SecondSplatValue || SecondPatternValue) &&
616 "Expected either splat value or pattern value.");
617
618 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
619 if (ForMemset) {
620 if (FirstSplatValue != SecondSplatValue)
621 continue;
622 } else {
623 if (FirstPatternValue != SecondPatternValue)
624 continue;
625 }
626 Tails.insert(SL[k]);
627 Heads.insert(SL[i]);
628 ConsecutiveChain[SL[i]] = SL[k];
629 break;
630 }
631 }
632 }
633
634 // We may run into multiple chains that merge into a single chain. We mark the
635 // stores that we transformed so that we don't visit the same store twice.
636 SmallPtrSet<Value *, 16> TransformedStores;
637 bool Changed = false;
638
639 // For stores that start but don't end a link in the chain:
640 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
641 it != e; ++it) {
642 if (Tails.count(*it))
643 continue;
644
645 // We found a store instr that starts a chain. Now follow the chain and try
646 // to transform it.
647 SmallPtrSet<Instruction *, 8> AdjacentStores;
648 StoreInst *I = *it;
649
650 StoreInst *HeadStore = I;
651 unsigned StoreSize = 0;
652
653 // Collect the chain into a list.
654 while (Tails.count(I) || Heads.count(I)) {
655 if (TransformedStores.count(I))
656 break;
657 AdjacentStores.insert(I);
658
659 StoreSize += getStoreSizeInBytes(I, DL);
660 // Move to the next value in the chain.
661 I = ConsecutiveChain[I];
662 }
663
664 Value *StoredVal = HeadStore->getValueOperand();
665 Value *StorePtr = HeadStore->getPointerOperand();
666 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000667 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000668
669 // Check to see if the stride matches the size of the stores. If so, then
670 // we know that every byte is touched in the loop.
671 if (StoreSize != Stride && StoreSize != -Stride)
672 continue;
673
674 bool NegStride = StoreSize == -Stride;
675
676 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
677 StoredVal, HeadStore, AdjacentStores, StoreEv,
678 BECount, NegStride)) {
679 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
680 Changed = true;
681 }
682 }
683
684 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000685}
686
Chris Lattner86438102011-01-04 07:46:33 +0000687/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000688bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
689 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000690 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000691 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
692 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000693
Chris Lattnere6b261f2011-02-18 22:22:15 +0000694 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000695 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000696 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000697
Chris Lattner86438102011-01-04 07:46:33 +0000698 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000699
Chris Lattner86438102011-01-04 07:46:33 +0000700 // See if the pointer expression is an AddRec like {base,+,1} on the current
701 // loop, which indicates a strided store. If we have something else, it's a
702 // random store we can't handle.
703 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000704 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000705 return false;
706
707 // Reject memsets that are so large that they overflow an unsigned.
708 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
709 if ((SizeInBytes >> 32) != 0)
710 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000711
Chris Lattner86438102011-01-04 07:46:33 +0000712 // Check to see if the stride matches the size of the memset. If so, then we
713 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000714 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
715 if (!ConstStride)
716 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000717
Chad Rosier81362a82016-02-12 21:03:23 +0000718 APInt Stride = ConstStride->getAPInt();
719 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000720 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000721
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000722 // Verify that the memset value is loop invariant. If not, we can't promote
723 // the memset.
724 Value *SplatValue = MSI->getValue();
725 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
726 return false;
727
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000728 SmallPtrSet<Instruction *, 1> MSIs;
729 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000730 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000731 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000732 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000733 BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000734}
735
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000736/// mayLoopAccessLocation - Return true if the specified loop might access the
737/// specified pointer location, which is a loop-strided access. The 'Access'
738/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000739static bool
740mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
741 const SCEV *BECount, unsigned StoreSize,
742 AliasAnalysis &AA,
743 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000744 // Get the location that may be stored across the loop. Since the access is
745 // strided positively through memory, we say that the modified location starts
746 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000747 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000748
749 // If the loop iterates a fixed number of times, we can refine the access size
750 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
751 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000752 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000753
754 // TODO: For this to be really effective, we have to dive into the pointer
755 // operand in the store. Store to &A[i] of 100 will always return may alias
756 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
757 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000758 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000759
760 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
761 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000762 for (Instruction &I : **BI)
763 if (IgnoredStores.count(&I) == 0 &&
764 (AA.getModRefInfo(&I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000765 return true;
766
767 return false;
768}
769
Chad Rosiered0c7d12015-11-13 19:11:07 +0000770// If we have a negative stride, Start refers to the end of the memory location
771// we're trying to memset. Therefore, we need to recompute the base pointer,
772// which is just Start - BECount*Size.
773static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
774 Type *IntPtr, unsigned StoreSize,
775 ScalarEvolution *SE) {
776 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
777 if (StoreSize != 1)
778 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
779 SCEV::FlagNUW);
780 return SE->getMinusSCEV(Start, Index);
781}
782
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000783/// Compute the number of bytes as a SCEV from the backedge taken count.
784///
785/// This also maps the SCEV into the provided type and tries to handle the
786/// computation in a way that will fold cleanly.
787static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
788 unsigned StoreSize, Loop *CurLoop,
789 const DataLayout *DL, ScalarEvolution *SE) {
790 const SCEV *NumBytesS;
791 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
792 // pointer size if it isn't already.
793 //
794 // If we're going to need to zero extend the BE count, check if we can add
795 // one to it prior to zero extending without overflow. Provided this is safe,
796 // it allows better simplification of the +1.
797 if (DL->getTypeSizeInBits(BECount->getType()) <
798 DL->getTypeSizeInBits(IntPtr) &&
799 SE->isLoopEntryGuardedByCond(
800 CurLoop, ICmpInst::ICMP_NE, BECount,
801 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
802 NumBytesS = SE->getZeroExtendExpr(
803 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
804 IntPtr);
805 } else {
806 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
807 SE->getOne(IntPtr), SCEV::FlagNUW);
808 }
809
810 // And scale it based on the store size.
811 if (StoreSize != 1) {
812 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
813 SCEV::FlagNUW);
814 }
815 return NumBytesS;
816}
817
Chris Lattner0f4a6402011-02-19 19:31:39 +0000818/// processLoopStridedStore - We see a strided store of some value. If we can
819/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000820bool LoopIdiomRecognize::processLoopStridedStore(
821 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000822 Value *StoredVal, Instruction *TheStore,
823 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000824 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000825 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000826 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000827
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000828 if (!SplatValue)
829 PatternValue = getMemSetPatternValue(StoredVal, DL);
830
831 assert((SplatValue || PatternValue) &&
832 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000833
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000834 // The trip count of the loop and the base pointer of the addrec SCEV is
835 // guaranteed to be loop invariant, which means that it should dominate the
836 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000837 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000838 BasicBlock *Preheader = CurLoop->getLoopPreheader();
839 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000840 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000841
Matt Arsenault009faed2013-09-11 05:09:42 +0000842 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000843 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000844
845 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000846 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000847 if (NegStride)
848 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000849
Aditya Kumar1c42d132017-05-05 14:49:45 +0000850 // TODO: ideally we should still be able to generate memset if SCEV expander
851 // is taught to generate the dependencies at the latest point.
852 if (!isSafeToExpand(Start, *SE))
853 return false;
854
Chris Lattner29e14ed2010-12-26 23:42:51 +0000855 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000856 // this into a memset in the loop preheader now if we want. However, this
857 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000858 // or write to the aliased location. Check for any overlap by generating the
859 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000860 Value *BasePtr =
861 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000862 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000863 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000864 Expander.clear();
865 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000866 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000867 return false;
868 }
869
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000870 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
871 return false;
872
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000873 // Okay, everything looks good, insert the memset.
874
Chandler Carruthbad690e2015-08-12 23:06:37 +0000875 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000876 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
Andrew Trick328b2232011-03-14 16:48:10 +0000877
Aditya Kumar1c42d132017-05-05 14:49:45 +0000878 // TODO: ideally we should still be able to generate memset if SCEV expander
879 // is taught to generate the dependencies at the latest point.
880 if (!isSafeToExpand(NumBytesS, *SE))
881 return false;
882
Andrew Trick328b2232011-03-14 16:48:10 +0000883 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000884 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000885
Devang Pateld00c6282011-03-07 22:43:45 +0000886 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000887 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000888 NewCall =
889 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000890 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000891 // Everything is emitted in default address space
892 Type *Int8PtrTy = DestInt8PtrTy;
893
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000894 Module *M = TheStore->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000895 Value *MSP =
896 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000897 Int8PtrTy, Int8PtrTy, IntPtr);
Ahmed Bougachaace97c12016-04-27 19:04:50 +0000898 inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000899
Chris Lattner0f4a6402011-02-19 19:31:39 +0000900 // Otherwise we should form a memset_pattern16. PatternValue is known to be
901 // an constant array of 16-bytes. Plop the value into a mergable global.
902 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000903 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000904 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000905 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000906 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000907 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000908 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000909 }
Andrew Trick328b2232011-03-14 16:48:10 +0000910
Chris Lattner29e14ed2010-12-26 23:42:51 +0000911 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000912 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000913 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000914
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000915 // Okay, the memset has been formed. Zap the original store and anything that
916 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000917 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000918 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000919 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000920 return true;
921}
922
Chad Rosier1cd3da12015-11-19 21:33:07 +0000923/// If the stored value is a strided load in the same loop with the same stride
924/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000925/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000926bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
927 const SCEV *BECount) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000928 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000929
930 Value *StorePtr = SI->getPointerOperand();
931 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000932 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000933 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
934 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000935
Chad Rosierfddc01f2015-11-19 18:22:21 +0000936 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000937 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000938 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000939
940 // See if the pointer expression is an AddRec like {base,+,1} on the current
941 // loop, which indicates a strided load. If we have something else, it's a
942 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000943 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000944 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000945
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000946 // The trip count of the loop and the base pointer of the addrec SCEV is
947 // guaranteed to be loop invariant, which means that it should dominate the
948 // header. This allows us to insert code for it in the preheader.
949 BasicBlock *Preheader = CurLoop->getLoopPreheader();
950 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000951 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000952
Chad Rosiercc299b62015-11-13 21:51:02 +0000953 const SCEV *StrStart = StoreEv->getStart();
954 unsigned StrAS = SI->getPointerAddressSpace();
955 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
956
957 // Handle negative strided loops.
958 if (NegStride)
959 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
960
Chris Lattner85b6d812011-01-02 03:37:56 +0000961 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000962 // this into a memcpy in the loop preheader now if we want. However, this
963 // would be unsafe to do if there is anything else in the loop that may read
964 // or write the memory region we're storing to. This includes the load that
965 // feeds the stores. Check for an alias by generating the base address and
966 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000967 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000968 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000969
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000970 SmallPtrSet<Instruction *, 1> Stores;
971 Stores.insert(SI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000972 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000973 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000974 Expander.clear();
975 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000976 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000977 return false;
978 }
979
Chad Rosiercc299b62015-11-13 21:51:02 +0000980 const SCEV *LdStart = LoadEv->getStart();
981 unsigned LdAS = LI->getPointerAddressSpace();
982
983 // Handle negative strided loops.
984 if (NegStride)
985 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
986
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000987 // For a memcpy, we have to make sure that the input array is not being
988 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000989 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000990 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000991
Chandler Carruth194f59c2015-07-22 23:15:57 +0000992 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000993 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000994 Expander.clear();
995 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000996 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
997 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000998 return false;
999 }
1000
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001001 if (avoidLIRForMultiBlockLoop())
1002 return false;
1003
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001004 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001005
Chandler Carruthbad690e2015-08-12 23:06:37 +00001006 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +00001007 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001008
1009 Value *NumBytes =
1010 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1011
Anna Thomasb2a212c2017-06-06 16:45:25 +00001012 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
1013 CallInst *NewCall = nullptr;
1014 // Check whether to generate an unordered atomic memcpy:
1015 // If the load or store are atomic, then they must neccessarily be unordered
1016 // by previous checks.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001017 if (!SI->isAtomic() && !LI->isAtomic())
Anna Thomasb2a212c2017-06-06 16:45:25 +00001018 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001019 else {
Anna Thomasb2a212c2017-06-06 16:45:25 +00001020 // We cannot allow unaligned ops for unordered load/store, so reject
1021 // anything where the alignment isn't at least the element size.
1022 if (Align < StoreSize)
1023 return false;
1024
1025 // If the element.atomic memcpy is not lowered into explicit
1026 // loads/stores later, then it will be lowered into an element-size
1027 // specific lib call. If the lib call doesn't exist for our store size, then
1028 // we shouldn't generate the memcpy.
1029 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1030 return false;
1031
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001032 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1033 StoreBasePtr, LoadBasePtr, NumBytes, StoreSize);
Anna Thomasb2a212c2017-06-06 16:45:25 +00001034
Anna Thomasb2a212c2017-06-06 16:45:25 +00001035 // Propagate alignment info onto the pointer args. Note that unordered
1036 // atomic loads/stores are *required* by the spec to have an alignment
1037 // but non-atomic loads/stores may not.
1038 NewCall->addParamAttr(0, Attribute::getWithAlignment(NewCall->getContext(),
1039 SI->getAlignment()));
1040 NewCall->addParamAttr(1, Attribute::getWithAlignment(NewCall->getContext(),
1041 LI->getAlignment()));
1042 }
Devang Patel0daa07e2011-05-04 21:37:05 +00001043 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001044
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001045 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001046 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1047 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001048
Chad Rosier7f08d802015-10-13 20:59:16 +00001049 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +00001050 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +00001051 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001052 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001053 return true;
1054}
Chandler Carruthd9c60702015-08-13 00:10:03 +00001055
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001056// When compiling for codesize we avoid idiom recognition for a multi-block loop
1057// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1058//
1059bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1060 bool IsLoopMemset) {
1061 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1062 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1063 DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1064 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1065 << " avoided: multi-block top-level loop\n");
1066 return true;
1067 }
1068 }
1069
1070 return false;
1071}
1072
Chandler Carruthd9c60702015-08-13 00:10:03 +00001073bool LoopIdiomRecognize::runOnNoncountableLoop() {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001074 return recognizePopcount() || recognizeAndInsertCTLZ();
Chandler Carruthd9c60702015-08-13 00:10:03 +00001075}
Chandler Carruth8219a502015-08-13 00:44:29 +00001076
1077/// Check if the given conditional branch is based on the comparison between
1078/// a variable and zero, and if the variable is non-zero, the control yields to
1079/// the loop entry. If the branch matches the behavior, the variable involved
Xin Tong8b8a6002017-01-05 21:40:08 +00001080/// in the comparison is returned. This function will be called to see if the
Chandler Carruth8219a502015-08-13 00:44:29 +00001081/// precondition and postcondition of the loop are in desirable form.
1082static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1083 if (!BI || !BI->isConditional())
1084 return nullptr;
1085
1086 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1087 if (!Cond)
1088 return nullptr;
1089
1090 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1091 if (!CmpZero || !CmpZero->isZero())
1092 return nullptr;
1093
1094 ICmpInst::Predicate Pred = Cond->getPredicate();
1095 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1096 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1097 return Cond->getOperand(0);
1098
1099 return nullptr;
1100}
1101
Davide Italiano4bc91192017-05-23 22:32:56 +00001102// Check if the recurrence variable `VarX` is in the right form to create
1103// the idiom. Returns the value coerced to a PHINode if so.
1104static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1105 BasicBlock *LoopEntry) {
1106 auto *PhiX = dyn_cast<PHINode>(VarX);
1107 if (PhiX && PhiX->getParent() == LoopEntry &&
1108 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1109 return PhiX;
1110 return nullptr;
1111}
1112
Chandler Carruth8219a502015-08-13 00:44:29 +00001113/// Return true iff the idiom is detected in the loop.
1114///
1115/// Additionally:
1116/// 1) \p CntInst is set to the instruction counting the population bit.
1117/// 2) \p CntPhi is set to the corresponding phi node.
1118/// 3) \p Var is set to the value whose population bits are being counted.
1119///
1120/// The core idiom we are trying to detect is:
1121/// \code
1122/// if (x0 != 0)
1123/// goto loop-exit // the precondition of the loop
1124/// cnt0 = init-val;
1125/// do {
1126/// x1 = phi (x0, x2);
1127/// cnt1 = phi(cnt0, cnt2);
1128///
1129/// cnt2 = cnt1 + 1;
1130/// ...
1131/// x2 = x1 & (x1 - 1);
1132/// ...
1133/// } while(x != 0);
1134///
1135/// loop-exit:
1136/// \endcode
1137static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1138 Instruction *&CntInst, PHINode *&CntPhi,
1139 Value *&Var) {
1140 // step 1: Check to see if the look-back branch match this pattern:
1141 // "if (a!=0) goto loop-entry".
1142 BasicBlock *LoopEntry;
1143 Instruction *DefX2, *CountInst;
1144 Value *VarX1, *VarX0;
1145 PHINode *PhiX, *CountPhi;
1146
1147 DefX2 = CountInst = nullptr;
1148 VarX1 = VarX0 = nullptr;
1149 PhiX = CountPhi = nullptr;
1150 LoopEntry = *(CurLoop->block_begin());
1151
1152 // step 1: Check if the loop-back branch is in desirable form.
1153 {
1154 if (Value *T = matchCondition(
1155 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1156 DefX2 = dyn_cast<Instruction>(T);
1157 else
1158 return false;
1159 }
1160
1161 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1162 {
1163 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1164 return false;
1165
1166 BinaryOperator *SubOneOp;
1167
1168 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1169 VarX1 = DefX2->getOperand(1);
1170 else {
1171 VarX1 = DefX2->getOperand(0);
1172 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1173 }
1174 if (!SubOneOp)
1175 return false;
1176
1177 Instruction *SubInst = cast<Instruction>(SubOneOp);
1178 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1179 if (!Dec ||
1180 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1181 (SubInst->getOpcode() == Instruction::Add &&
Craig Topper79ab6432017-07-06 18:39:47 +00001182 Dec->isMinusOne()))) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001183 return false;
1184 }
1185 }
1186
1187 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001188 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1189 if (!PhiX)
1190 return false;
Chandler Carruth8219a502015-08-13 00:44:29 +00001191
1192 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1193 {
1194 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001195 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001196 IterE = LoopEntry->end();
1197 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001198 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001199 if (Inst->getOpcode() != Instruction::Add)
1200 continue;
1201
1202 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1203 if (!Inc || !Inc->isOne())
1204 continue;
1205
Davide Italiano7bf95b92017-05-23 23:51:54 +00001206 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1207 if (!Phi)
Chandler Carruth8219a502015-08-13 00:44:29 +00001208 continue;
1209
1210 // Check if the result of the instruction is live of the loop.
1211 bool LiveOutLoop = false;
1212 for (User *U : Inst->users()) {
1213 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1214 LiveOutLoop = true;
1215 break;
1216 }
1217 }
1218
1219 if (LiveOutLoop) {
1220 CountInst = Inst;
1221 CountPhi = Phi;
1222 break;
1223 }
1224 }
1225
1226 if (!CountInst)
1227 return false;
1228 }
1229
1230 // step 5: check if the precondition is in this form:
1231 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1232 {
1233 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1234 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1235 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1236 return false;
1237
1238 CntInst = CountInst;
1239 CntPhi = CountPhi;
1240 Var = T;
1241 }
1242
1243 return true;
1244}
1245
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001246/// Return true if the idiom is detected in the loop.
1247///
1248/// Additionally:
1249/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1250/// or nullptr if there is no such.
1251/// 2) \p CntPhi is set to the corresponding phi node
1252/// or nullptr if there is no such.
1253/// 3) \p Var is set to the value whose CTLZ could be used.
1254/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1255///
1256/// The core idiom we are trying to detect is:
1257/// \code
1258/// if (x0 == 0)
1259/// goto loop-exit // the precondition of the loop
1260/// cnt0 = init-val;
1261/// do {
1262/// x = phi (x0, x.next); //PhiX
1263/// cnt = phi(cnt0, cnt.next);
1264///
1265/// cnt.next = cnt + 1;
1266/// ...
1267/// x.next = x >> 1; // DefX
1268/// ...
1269/// } while(x.next != 0);
1270///
1271/// loop-exit:
1272/// \endcode
1273static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX,
1274 Instruction *&CntInst, PHINode *&CntPhi,
1275 Instruction *&DefX) {
1276 BasicBlock *LoopEntry;
1277 Value *VarX = nullptr;
1278
1279 DefX = nullptr;
1280 PhiX = nullptr;
1281 CntInst = nullptr;
1282 CntPhi = nullptr;
1283 LoopEntry = *(CurLoop->block_begin());
1284
1285 // step 1: Check if the loop-back branch is in desirable form.
1286 if (Value *T = matchCondition(
1287 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1288 DefX = dyn_cast<Instruction>(T);
1289 else
1290 return false;
1291
1292 // step 2: detect instructions corresponding to "x.next = x >> 1"
1293 if (!DefX || DefX->getOpcode() != Instruction::AShr)
1294 return false;
1295 if (ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)))
1296 if (!Shft || !Shft->isOne())
1297 return false;
1298 VarX = DefX->getOperand(0);
1299
1300 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001301 PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1302 if (!PhiX)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001303 return false;
1304
1305 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1306 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1307 // then all uses of "cnt.next" could be optimized to the trip count
1308 // plus "cnt0". Currently it is not optimized.
1309 // This step could be used to detect POPCNT instruction:
1310 // cnt.next = cnt + (x.next & 1)
1311 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1312 IterE = LoopEntry->end();
1313 Iter != IterE; Iter++) {
1314 Instruction *Inst = &*Iter;
1315 if (Inst->getOpcode() != Instruction::Add)
1316 continue;
1317
1318 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1319 if (!Inc || !Inc->isOne())
1320 continue;
1321
Davide Italiano7bf95b92017-05-23 23:51:54 +00001322 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1323 if (!Phi)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001324 continue;
1325
1326 CntInst = Inst;
1327 CntPhi = Phi;
1328 break;
1329 }
1330 if (!CntInst)
1331 return false;
1332
1333 return true;
1334}
1335
1336/// Recognize CTLZ idiom in a non-countable loop and convert the loop
1337/// to countable (with CTLZ trip count).
1338/// If CTLZ inserted as a new trip count returns true; otherwise, returns false.
1339bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1340 // Give up if the loop has multiple blocks or multiple backedges.
1341 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1342 return false;
1343
1344 Instruction *CntInst, *DefX;
1345 PHINode *CntPhi, *PhiX;
1346 if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX))
1347 return false;
1348
1349 bool IsCntPhiUsedOutsideLoop = false;
1350 for (User *U : CntPhi->users())
1351 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1352 IsCntPhiUsedOutsideLoop = true;
1353 break;
1354 }
1355 bool IsCntInstUsedOutsideLoop = false;
1356 for (User *U : CntInst->users())
1357 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1358 IsCntInstUsedOutsideLoop = true;
1359 break;
1360 }
1361 // If both CntInst and CntPhi are used outside the loop the profitability
1362 // is questionable.
1363 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1364 return false;
1365
1366 // For some CPUs result of CTLZ(X) intrinsic is undefined
1367 // when X is 0. If we can not guarantee X != 0, we need to check this
1368 // when expand.
1369 bool ZeroCheck = false;
1370 // It is safe to assume Preheader exist as it was checked in
1371 // parent function RunOnLoop.
1372 BasicBlock *PH = CurLoop->getLoopPreheader();
1373 Value *InitX = PhiX->getIncomingValueForBlock(PH);
1374 // If we check X != 0 before entering the loop we don't need a zero
Evgeny Stupachenkocc195602017-05-16 21:44:59 +00001375 // check in CTLZ intrinsic, but only if Cnt Phi is not used outside of the
1376 // loop (if it is used we count CTLZ(X >> 1)).
1377 if (!IsCntPhiUsedOutsideLoop)
1378 if (BasicBlock *PreCondBB = PH->getSinglePredecessor())
1379 if (BranchInst *PreCondBr =
1380 dyn_cast<BranchInst>(PreCondBB->getTerminator())) {
1381 if (matchCondition(PreCondBr, PH) == InitX)
1382 ZeroCheck = true;
1383 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001384
1385 // Check if CTLZ intrinsic is profitable. Assume it is always profitable
1386 // if we delete the loop (the loop has only 6 instructions):
1387 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1388 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1389 // %shr = ashr %n.addr.0, 1
1390 // %tobool = icmp eq %shr, 0
1391 // %inc = add nsw %i.0, 1
1392 // br i1 %tobool
1393
1394 IRBuilder<> Builder(PH->getTerminator());
1395 SmallVector<const Value *, 2> Ops =
1396 {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()};
1397 ArrayRef<const Value *> Args(Ops);
1398 if (CurLoop->getHeader()->size() != 6 &&
1399 TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) >
1400 TargetTransformInfo::TCC_Basic)
1401 return false;
1402
1403 const DebugLoc DL = DefX->getDebugLoc();
1404 transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck,
1405 IsCntPhiUsedOutsideLoop);
1406 return true;
1407}
1408
Chandler Carruth8219a502015-08-13 00:44:29 +00001409/// Recognizes a population count idiom in a non-countable loop.
1410///
1411/// If detected, transforms the relevant code to issue the popcount intrinsic
1412/// function call, and returns true; otherwise, returns false.
1413bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001414 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1415 return false;
1416
1417 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001418 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001419 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1420 // in a compact loop.
1421
Renato Golin655348f2015-08-13 11:25:38 +00001422 // Give up if the loop has multiple blocks or multiple backedges.
1423 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001424 return false;
1425
Renato Golin655348f2015-08-13 11:25:38 +00001426 BasicBlock *LoopBody = *(CurLoop->block_begin());
1427 if (LoopBody->size() >= 20) {
1428 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001429 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001430 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001431
1432 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001433 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001434 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001435 return false;
1436 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001437 if (!EntryBI || EntryBI->isConditional())
1438 return false;
1439
1440 // It should have a precondition block where the generated popcount instrinsic
1441 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001442 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001443 if (!PreCondBB)
1444 return false;
1445 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1446 if (!PreCondBI || PreCondBI->isUnconditional())
1447 return false;
1448
1449 Instruction *CntInst;
1450 PHINode *CntPhi;
1451 Value *Val;
1452 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1453 return false;
1454
1455 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1456 return true;
1457}
1458
1459static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001460 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001461 Value *Ops[] = {Val};
1462 Type *Tys[] = {Val->getType()};
1463
1464 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1465 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1466 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1467 CI->setDebugLoc(DL);
1468
1469 return CI;
1470}
1471
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001472static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1473 const DebugLoc &DL, bool ZeroCheck) {
1474 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1475 Type *Tys[] = {Val->getType()};
1476
1477 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1478 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys);
1479 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1480 CI->setDebugLoc(DL);
1481
1482 return CI;
1483}
1484
1485/// Transform the following loop:
1486/// loop:
1487/// CntPhi = PHI [Cnt0, CntInst]
1488/// PhiX = PHI [InitX, DefX]
1489/// CntInst = CntPhi + 1
1490/// DefX = PhiX >> 1
1491// LOOP_BODY
1492/// Br: loop if (DefX != 0)
1493/// Use(CntPhi) or Use(CntInst)
1494///
1495/// Into:
1496/// If CntPhi used outside the loop:
1497/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1498/// Count = CountPrev + 1
1499/// else
1500/// Count = BitWidth(InitX) - CTLZ(InitX)
1501/// loop:
1502/// CntPhi = PHI [Cnt0, CntInst]
1503/// PhiX = PHI [InitX, DefX]
1504/// PhiCount = PHI [Count, Dec]
1505/// CntInst = CntPhi + 1
1506/// DefX = PhiX >> 1
1507/// Dec = PhiCount - 1
1508/// LOOP_BODY
1509/// Br: loop if (Dec != 0)
1510/// Use(CountPrev + Cnt0) // Use(CntPhi)
1511/// or
1512/// Use(Count + Cnt0) // Use(CntInst)
1513///
1514/// If LOOP_BODY is empty the loop will be deleted.
1515/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1516void LoopIdiomRecognize::transformLoopToCountable(
1517 BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX,
1518 const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1519 BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1520
1521 // Step 1: Insert the CTLZ instruction at the end of the preheader block
1522 // Count = BitWidth - CTLZ(InitX);
1523 // If there are uses of CntPhi create:
1524 // CountPrev = BitWidth - CTLZ(InitX >> 1);
1525 IRBuilder<> Builder(PreheaderBr);
1526 Builder.SetCurrentDebugLocation(DL);
1527 Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1528
1529 if (IsCntPhiUsedOutsideLoop)
1530 InitXNext = Builder.CreateAShr(InitX,
1531 ConstantInt::get(InitX->getType(), 1));
1532 else
1533 InitXNext = InitX;
1534 CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck);
1535 Count = Builder.CreateSub(
1536 ConstantInt::get(CTLZ->getType(),
1537 CTLZ->getType()->getIntegerBitWidth()),
1538 CTLZ);
1539 if (IsCntPhiUsedOutsideLoop) {
1540 CountPrev = Count;
1541 Count = Builder.CreateAdd(
1542 CountPrev,
1543 ConstantInt::get(CountPrev->getType(), 1));
1544 }
1545 if (IsCntPhiUsedOutsideLoop)
1546 NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1547 cast<IntegerType>(CntInst->getType()));
1548 else
1549 NewCount = Builder.CreateZExtOrTrunc(Count,
1550 cast<IntegerType>(CntInst->getType()));
1551
1552 // If the CTLZ counter's initial value is not zero, insert Add Inst.
1553 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1554 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1555 if (!InitConst || !InitConst->isZero())
1556 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1557
1558 // Step 2: Insert new IV and loop condition:
1559 // loop:
1560 // ...
1561 // PhiCount = PHI [Count, Dec]
1562 // ...
1563 // Dec = PhiCount - 1
1564 // ...
1565 // Br: loop if (Dec != 0)
1566 BasicBlock *Body = *(CurLoop->block_begin());
1567 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1568 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1569 Type *Ty = Count->getType();
1570
1571 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1572
1573 Builder.SetInsertPoint(LbCond);
1574 Instruction *TcDec = cast<Instruction>(
1575 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1576 "tcdec", false, true));
1577
1578 TcPhi->addIncoming(Count, Preheader);
1579 TcPhi->addIncoming(TcDec, Body);
1580
1581 CmpInst::Predicate Pred =
1582 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1583 LbCond->setPredicate(Pred);
1584 LbCond->setOperand(0, TcDec);
1585 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1586
1587 // Step 3: All the references to the original counter outside
1588 // the loop are replaced with the NewCount -- the value returned from
1589 // __builtin_ctlz(x).
1590 if (IsCntPhiUsedOutsideLoop)
1591 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1592 else
1593 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1594
1595 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1596 // loop. The loop would otherwise not be deleted even if it becomes empty.
1597 SE->forgetLoop(CurLoop);
1598}
1599
Chandler Carruth8219a502015-08-13 00:44:29 +00001600void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1601 Instruction *CntInst,
1602 PHINode *CntPhi, Value *Var) {
1603 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1604 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1605 const DebugLoc DL = CntInst->getDebugLoc();
1606
1607 // Assuming before transformation, the loop is following:
1608 // if (x) // the precondition
1609 // do { cnt++; x &= x - 1; } while(x);
1610
1611 // Step 1: Insert the ctpop instruction at the end of the precondition block
1612 IRBuilder<> Builder(PreCondBr);
1613 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1614 {
1615 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1616 NewCount = PopCntZext =
1617 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1618
1619 if (NewCount != PopCnt)
1620 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1621
1622 // TripCnt is exactly the number of iterations the loop has
1623 TripCnt = NewCount;
1624
1625 // If the population counter's initial value is not zero, insert Add Inst.
1626 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1627 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1628 if (!InitConst || !InitConst->isZero()) {
1629 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1630 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1631 }
1632 }
1633
Nick Lewycky2c852542015-08-19 06:22:33 +00001634 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001635 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001636 // function would be partial dead code, and downstream passes will drag
1637 // it back from the precondition block to the preheader.
1638 {
1639 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1640
1641 Value *Opnd0 = PopCntZext;
1642 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1643 if (PreCond->getOperand(0) != Var)
1644 std::swap(Opnd0, Opnd1);
1645
1646 ICmpInst *NewPreCond = cast<ICmpInst>(
1647 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1648 PreCondBr->setCondition(NewPreCond);
1649
1650 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1651 }
1652
1653 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001654 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001655 // loop into a countable one. The benefit is twofold:
1656 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001657 // - If the loop only counts population, the entire loop becomes dead after
1658 // the transformation. It is a lot easier to prove a countable loop dead
1659 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001660 // isn't dead even if it computes nothing useful. In general, DCE needs
1661 // to prove a noncountable loop finite before safely delete it.)
1662 //
1663 // - If the loop also performs something else, it remains alive.
1664 // Since it is transformed to countable form, it can be aggressively
1665 // optimized by some optimizations which are in general not applicable
1666 // to a noncountable loop.
1667 //
1668 // After this step, this loop (conceptually) would look like following:
1669 // newcnt = __builtin_ctpop(x);
1670 // t = newcnt;
1671 // if (x)
1672 // do { cnt++; x &= x-1; t--) } while (t > 0);
1673 BasicBlock *Body = *(CurLoop->block_begin());
1674 {
1675 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1676 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1677 Type *Ty = TripCnt->getType();
1678
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001679 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001680
1681 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001682 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001683 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1684 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001685
1686 TcPhi->addIncoming(TripCnt, PreHead);
1687 TcPhi->addIncoming(TcDec, Body);
1688
1689 CmpInst::Predicate Pred =
1690 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1691 LbCond->setPredicate(Pred);
1692 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001693 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001694 }
1695
1696 // Step 4: All the references to the original population counter outside
1697 // the loop are replaced with the NewCount -- the value returned from
1698 // __builtin_ctpop().
1699 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1700
1701 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1702 // loop. The loop would otherwise not be deleted even if it becomes empty.
1703 SE->forgetLoop(CurLoop);
1704}