blob: f7dab9f382bfce0c574daad711a7c99056e28984 [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner81ae3f22010-12-26 19:39:38 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements an idiom recognizer that transforms simple loops into a
10// non-loop form. In cases that this kicks in, it can be a significant
11// performance win.
12//
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000013// If compiling for code size we avoid idiom recognition if the resulting
14// code could be larger than the code for the original loop. One way this could
15// happen is if the loop is not removable after idiom recognition due to the
16// presence of non-idiom instructions. The initial implementation of the
17// heuristics applies to idioms in multi-block loops.
18//
Chris Lattner81ae3f22010-12-26 19:39:38 +000019//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000020//
21// TODO List:
22//
23// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000024// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000025// Future floating point idioms to recognize in -ffast-math mode:
26// fpowi
27// Future integer operation idioms to recognize:
Craig Topperc9a60002018-12-26 21:59:48 +000028// ctpop
Chris Lattner0469e012011-01-02 18:32:09 +000029//
30// Beware that isel's default lowering for ctpop is highly inefficient for
31// i64 and larger types when i64 is legal and the value has few bits set. It
32// would be good to enhance isel to emit a loop for ctpop in this case.
33//
Chris Lattner02a97762011-01-03 01:10:08 +000034// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000035// replace them with calls to BLAS (if linked in??).
36//
Chris Lattner0469e012011-01-02 18:32:09 +000037//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000038
Roman Lebedevfae2e462019-05-30 13:01:53 +000039#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000040#include "llvm/ADT/APInt.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000043#include "llvm/ADT/MapVector.h"
44#include "llvm/ADT/SetVector.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000045#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000048#include "llvm/ADT/StringRef.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000049#include "llvm/Analysis/AliasAnalysis.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000050#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000051#include "llvm/Analysis/LoopInfo.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000052#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000053#include "llvm/Analysis/MemoryLocation.h"
Roman Lebedeve8578952019-05-30 13:02:06 +000054#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000055#include "llvm/Analysis/ScalarEvolution.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000056#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000057#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000059#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000060#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000061#include "llvm/IR/Attributes.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/DataLayout.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000066#include "llvm/IR/DebugLoc.h"
67#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000068#include "llvm/IR/Dominators.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000069#include "llvm/IR/GlobalValue.h"
70#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000071#include "llvm/IR/IRBuilder.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000072#include "llvm/IR/InstrTypes.h"
73#include "llvm/IR/Instruction.h"
74#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000075#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000076#include "llvm/IR/Intrinsics.h"
77#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/Module.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000079#include "llvm/IR/PassManager.h"
80#include "llvm/IR/Type.h"
81#include "llvm/IR/User.h"
82#include "llvm/IR/Value.h"
83#include "llvm/IR/ValueHandle.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080084#include "llvm/InitializePasses.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000085#include "llvm/Pass.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Support/Debug.h"
89#include "llvm/Support/raw_ostream.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000090#include "llvm/Transforms/Scalar.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000091#include "llvm/Transforms/Utils/BuildLibCalls.h"
Roman Lebedevfae2e462019-05-30 13:01:53 +000092#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000093#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000094#include <algorithm>
95#include <cassert>
96#include <cstdint>
97#include <utility>
98#include <vector>
99
Chris Lattner81ae3f22010-12-26 19:39:38 +0000100using namespace llvm;
101
Chandler Carruth964daaa2014-04-22 02:55:47 +0000102#define DEBUG_TYPE "loop-idiom"
103
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000104STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
105STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +0000106
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000107static cl::opt<bool> UseLIRCodeSizeHeurs(
108 "use-lir-code-size-heurs",
109 cl::desc("Use loop idiom recognition code size heuristics when compiling"
110 "with -Os/-Oz"),
111 cl::init(true), cl::Hidden);
112
Chris Lattner81ae3f22010-12-26 19:39:38 +0000113namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000114
Dehao Chenb9f8e292016-07-12 18:45:51 +0000115class LoopIdiomRecognize {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000116 Loop *CurLoop = nullptr;
Chandler Carruthbf143e22015-08-14 00:21:10 +0000117 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000118 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +0000119 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000120 ScalarEvolution *SE;
121 TargetLibraryInfo *TLI;
122 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +0000123 const DataLayout *DL;
Roman Lebedeve8578952019-05-30 13:02:06 +0000124 OptimizationRemarkEmitter &ORE;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000125 bool ApplyCodeSizeHeuristics;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000126
Chandler Carruthbad690e2015-08-12 23:06:37 +0000127public:
Dehao Chenb9f8e292016-07-12 18:45:51 +0000128 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
129 LoopInfo *LI, ScalarEvolution *SE,
130 TargetLibraryInfo *TLI,
131 const TargetTransformInfo *TTI,
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300132 const DataLayout *DL,
Roman Lebedeve8578952019-05-30 13:02:06 +0000133 OptimizationRemarkEmitter &ORE)
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300134 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {}
Chris Lattner81ae3f22010-12-26 19:39:38 +0000135
Dehao Chenb9f8e292016-07-12 18:45:51 +0000136 bool runOnLoop(Loop *L);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000137
Chandler Carruthbad690e2015-08-12 23:06:37 +0000138private:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000139 using StoreList = SmallVector<StoreInst *, 8>;
140 using StoreListMap = MapVector<Value *, StoreList>;
141
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000142 StoreListMap StoreRefsForMemset;
143 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000144 StoreList StoreRefsForMemcpy;
145 bool HasMemset;
146 bool HasMemsetPattern;
147 bool HasMemcpy;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000148
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000149 /// Return code for isLegalStore()
150 enum LegalStoreKind {
Anna Thomasae3f752f2017-05-19 18:00:30 +0000151 None = 0,
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000152 Memset,
153 MemsetPattern,
154 Memcpy,
Anna Thomasb2a212c2017-06-06 16:45:25 +0000155 UnorderedAtomicMemcpy,
Anna Thomasae3f752f2017-05-19 18:00:30 +0000156 DontUse // Dummy retval never to be used. Allows catching errors in retval
157 // handling.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000158 };
Chad Rosiercc9030b2015-11-11 23:00:59 +0000159
Chandler Carruthd9c60702015-08-13 00:10:03 +0000160 /// \name Countable Loop Idiom Handling
161 /// @{
162
Chandler Carruthbad690e2015-08-12 23:06:37 +0000163 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000164 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
165 SmallVectorImpl<BasicBlock *> &ExitBlocks);
166
Chad Rosiercc9030b2015-11-11 23:00:59 +0000167 void collectStores(BasicBlock *BB);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000168 LegalStoreKind isLegalStore(StoreInst *SI);
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000169 enum class ForMemset { No, Yes };
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000170 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000171 ForMemset For);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000172 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
173
174 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000175 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000176 Instruction *TheStore,
177 SmallPtrSetImpl<Instruction *> &Stores,
178 const SCEVAddRecExpr *Ev, const SCEV *BECount,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000179 bool NegStride, bool IsLoopMemset = false);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000180 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000181 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
182 bool IsLoopMemset = false);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000183
184 /// @}
185 /// \name Noncountable Loop Idiom Handling
186 /// @{
187
188 bool runOnNoncountableLoop();
189
Chandler Carruth8219a502015-08-13 00:44:29 +0000190 bool recognizePopcount();
191 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
192 PHINode *CntPhi, Value *Var);
Craig Topperc9a60002018-12-26 21:59:48 +0000193 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz
194 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
195 Instruction *CntInst, PHINode *CntPhi,
196 Value *Var, Instruction *DefX,
Craig Topper28352782018-07-08 01:45:47 +0000197 const DebugLoc &DL, bool ZeroCheck,
198 bool IsCntPhiUsedOutsideLoop);
Chandler Carruth8219a502015-08-13 00:44:29 +0000199
Chandler Carruthd9c60702015-08-13 00:10:03 +0000200 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000201};
202
Dehao Chenb9f8e292016-07-12 18:45:51 +0000203class LoopIdiomRecognizeLegacyPass : public LoopPass {
204public:
205 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000206
Dehao Chenb9f8e292016-07-12 18:45:51 +0000207 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
208 initializeLoopIdiomRecognizeLegacyPassPass(
209 *PassRegistry::getPassRegistry());
210 }
211
212 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
213 if (skipLoop(L))
214 return false;
215
216 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
217 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
218 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
219 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
220 TargetLibraryInfo *TLI =
Teresa Johnson9c27b592019-09-07 03:09:36 +0000221 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
222 *L->getHeader()->getParent());
Dehao Chenb9f8e292016-07-12 18:45:51 +0000223 const TargetTransformInfo *TTI =
224 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
225 *L->getHeader()->getParent());
226 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
227
Roman Lebedeve8578952019-05-30 13:02:06 +0000228 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
229 // pass. Function analyses need to be preserved across loop transformations
230 // but ORE cannot be preserved (see comment before the pass definition).
231 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
232
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300233 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL, ORE);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000234 return LIR.runOnLoop(L);
235 }
236
237 /// This transformation requires natural loop information & requires that
238 /// loop preheaders be inserted into the CFG.
Dehao Chenb9f8e292016-07-12 18:45:51 +0000239 void getAnalysisUsage(AnalysisUsage &AU) const override {
240 AU.addRequired<TargetLibraryInfoWrapperPass>();
241 AU.addRequired<TargetTransformInfoWrapperPass>();
242 getLoopAnalysisUsage(AU);
243 }
244};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000245
246} // end anonymous namespace
247
248char LoopIdiomRecognizeLegacyPass::ID = 0;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000249
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000250PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
251 LoopStandardAnalysisResults &AR,
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300252 LPMUpdater &) {
Dehao Chenb9f8e292016-07-12 18:45:51 +0000253 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
Dehao Chenb9f8e292016-07-12 18:45:51 +0000254
Roman Lebedeve8578952019-05-30 13:02:06 +0000255 const auto &FAM =
256 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
257 Function *F = L.getHeader()->getParent();
258
259 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
260 // FIXME: This should probably be optional rather than required.
261 if (!ORE)
262 report_fatal_error(
263 "LoopIdiomRecognizePass: OptimizationRemarkEmitterAnalysis not cached "
264 "at a higher level");
265
266 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL,
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300267 *ORE);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000268 if (!LIR.runOnLoop(&L))
269 return PreservedAnalyses::all();
270
271 return getLoopPassPreservedAnalyses();
272}
273
Dehao Chenb9f8e292016-07-12 18:45:51 +0000274INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
275 "Recognize loop idioms", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000276INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000277INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000278INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Dehao Chenb9f8e292016-07-12 18:45:51 +0000279INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
280 "Recognize loop idioms", false, false)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000281
Dehao Chenb9f8e292016-07-12 18:45:51 +0000282Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000283
David Majnemerc5601df2016-06-20 16:03:25 +0000284static void deleteDeadInstruction(Instruction *I) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000285 I->replaceAllUsesWith(UndefValue::get(I->getType()));
286 I->eraseFromParent();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000287}
288
Shuxin Yang95de7c32012-12-09 03:12:46 +0000289//===----------------------------------------------------------------------===//
290//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000291// Implementation of LoopIdiomRecognize
292//
293//===----------------------------------------------------------------------===//
294
Dehao Chenb9f8e292016-07-12 18:45:51 +0000295bool LoopIdiomRecognize::runOnLoop(Loop *L) {
Chandler Carruthd9c60702015-08-13 00:10:03 +0000296 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000297 // If the loop could not be converted to canonical form, it must have an
298 // indirectbr in it, just give up.
299 if (!L->getLoopPreheader())
300 return false;
301
302 // Disable loop idiom recognition if the function's name is a common idiom.
303 StringRef Name = L->getHeader()->getParent()->getName();
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300304 if (Name == "memset" || Name == "memcpy")
Chandler Carruthd9c60702015-08-13 00:10:03 +0000305 return false;
306
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000307 // Determine if code size heuristics need to be applied.
308 ApplyCodeSizeHeuristics =
Evandro Menezes85bd3972019-04-04 22:40:06 +0000309 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000310
David L. Jonesd21529f2017-01-23 23:16:46 +0000311 HasMemset = TLI->has(LibFunc_memset);
312 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
313 HasMemcpy = TLI->has(LibFunc_memcpy);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000314
Roman Lebedevc4b757b2019-11-02 12:39:02 +0300315 if (HasMemset || HasMemsetPattern || HasMemcpy)
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000316 if (SE->hasLoopInvariantBackedgeTakenCount(L))
317 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000318
Chandler Carruthd9c60702015-08-13 00:10:03 +0000319 return runOnNoncountableLoop();
320}
321
Shuxin Yang95de7c32012-12-09 03:12:46 +0000322bool LoopIdiomRecognize::runOnCountableLoop() {
323 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000324 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000325 "runOnCountableLoop() called on a loop without a predictable"
326 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000327
328 // If this loop executes exactly one time, then it should be peeled, not
329 // optimized by this pass.
330 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000331 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000332 return false;
333
Chandler Carruthbad690e2015-08-12 23:06:37 +0000334 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000335 CurLoop->getUniqueExitBlocks(ExitBlocks);
336
Roman Lebedev95dec502019-05-29 20:11:53 +0000337 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000338 << CurLoop->getHeader()->getParent()->getName()
Roman Lebedev95dec502019-05-29 20:11:53 +0000339 << "] Countable Loop %" << CurLoop->getHeader()->getName()
340 << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000341
342 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000343
344 // The following transforms hoist stores/memsets into the loop pre-header.
345 // Give up if the loop has instructions may throw.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000346 SimpleLoopSafetyInfo SafetyInfo;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000347 SafetyInfo.computeLoopSafetyInfo(CurLoop);
348 if (SafetyInfo.anyBlockMayThrow())
Haicheng Wua95cd1262016-07-06 21:05:40 +0000349 return MadeChange;
350
Shuxin Yang95de7c32012-12-09 03:12:46 +0000351 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000352 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000353 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000354 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000355 continue;
356
Davide Italiano80625af2015-05-13 19:51:21 +0000357 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000358 }
359 return MadeChange;
360}
361
Chad Rosier4acff962016-02-12 19:05:27 +0000362static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000363 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000364 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000365}
366
Chad Rosier94274fb2015-12-21 14:49:32 +0000367/// getMemSetPatternValue - If a strided store of the specified value is safe to
368/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
369/// be passed in. Otherwise, return null.
370///
371/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
372/// just replicate their input array and then pass on to memset_pattern16.
373static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000374 // FIXME: This could check for UndefValue because it can be merged into any
375 // other valid pattern.
376
Chad Rosier94274fb2015-12-21 14:49:32 +0000377 // If the value isn't a constant, we can't promote it to being in a constant
378 // array. We could theoretically do a store to an alloca or something, but
379 // that doesn't seem worthwhile.
380 Constant *C = dyn_cast<Constant>(V);
381 if (!C)
382 return nullptr;
383
384 // Only handle simple values that are a power of two bytes in size.
385 uint64_t Size = DL->getTypeSizeInBits(V->getType());
386 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
387 return nullptr;
388
389 // Don't care enough about darwin/ppc to implement this.
390 if (DL->isBigEndian())
391 return nullptr;
392
393 // Convert to size in bytes.
394 Size /= 8;
395
396 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
397 // if the top and bottom are the same (e.g. for vectors and large integers).
398 if (Size > 16)
399 return nullptr;
400
401 // If the constant is exactly 16 bytes, just use it.
402 if (Size == 16)
403 return C;
404
405 // Otherwise, we'll use an array of the constants.
406 unsigned ArraySize = 16 / Size;
407 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
408 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
409}
410
Anna Thomasae3f752f2017-05-19 18:00:30 +0000411LoopIdiomRecognize::LegalStoreKind
412LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Chad Rosier869962f2015-12-01 14:26:35 +0000413 // Don't touch volatile stores.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000414 if (SI->isVolatile())
415 return LegalStoreKind::None;
416 // We only want simple or unordered-atomic stores.
417 if (!SI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000418 return LegalStoreKind::None;
Chad Rosier869962f2015-12-01 14:26:35 +0000419
Sanjoy Das206f65c2017-04-24 20:12:10 +0000420 // Don't convert stores of non-integral pointer types to memsets (which stores
421 // integers).
422 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000423 return LegalStoreKind::None;
Sanjoy Das206f65c2017-04-24 20:12:10 +0000424
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000425 // Avoid merging nontemporal stores.
426 if (SI->getMetadata(LLVMContext::MD_nontemporal))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000427 return LegalStoreKind::None;
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000428
Chad Rosiera548fe52015-11-12 19:09:16 +0000429 Value *StoredVal = SI->getValueOperand();
430 Value *StorePtr = SI->getPointerOperand();
431
432 // Reject stores that are so large that they overflow an unsigned.
433 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
434 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000435 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000436
437 // See if the pointer expression is an AddRec like {base,+,1} on the current
438 // loop, which indicates a strided store. If we have something else, it's a
439 // random store we can't handle.
440 const SCEVAddRecExpr *StoreEv =
441 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
442 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000443 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000444
445 // Check to see if we have a constant stride.
446 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000447 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000448
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000449 // See if the store can be turned into a memset.
450
451 // If the stored value is a byte-wise value (like i32 -1), then it may be
452 // turned into a memset of i8 -1, assuming that all the consecutive bytes
453 // are stored. A store of i32 0x01020304 can never be turned into a memset,
454 // but it can be turned into memset_pattern if the target supports it.
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000455 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000456 Constant *PatternValue = nullptr;
457
Anna Thomasb2a212c2017-06-06 16:45:25 +0000458 // Note: memset and memset_pattern on unordered-atomic is yet not supported
459 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
460
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000461 // If we're allowed to form a memset, and the stored value would be
462 // acceptable for memset, use it.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000463 if (!UnorderedAtomic && HasMemset && SplatValue &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000464 // Verify that the stored value is loop invariant. If not, we can't
465 // promote the memset.
466 CurLoop->isLoopInvariant(SplatValue)) {
467 // It looks like we can use SplatValue.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000468 return LegalStoreKind::Memset;
Anna Thomasb2a212c2017-06-06 16:45:25 +0000469 } else if (!UnorderedAtomic && HasMemsetPattern &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000470 // Don't create memset_pattern16s with address spaces.
471 StorePtr->getType()->getPointerAddressSpace() == 0 &&
472 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
473 // It looks like we can use PatternValue!
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000474 return LegalStoreKind::MemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000475 }
476
477 // Otherwise, see if the store can be turned into a memcpy.
478 if (HasMemcpy) {
479 // Check to see if the stride matches the size of the store. If so, then we
480 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000481 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000482 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000483 if (StoreSize != Stride && StoreSize != -Stride)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000484 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000485
486 // The store must be feeding a non-volatile load.
487 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000488
489 // Only allow non-volatile loads
490 if (!LI || LI->isVolatile())
491 return LegalStoreKind::None;
492 // Only allow simple or unordered-atomic loads
493 if (!LI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000494 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000495
496 // See if the pointer expression is an AddRec like {base,+,1} on the current
497 // loop, which indicates a strided load. If we have something else, it's a
498 // random load we can't handle.
499 const SCEVAddRecExpr *LoadEv =
500 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
501 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000502 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000503
504 // The store and load must share the same stride.
505 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000506 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000507
508 // Success. This store can be converted into a memcpy.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000509 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
510 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
511 : LegalStoreKind::Memcpy;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000512 }
513 // This store can't be transformed into a memset/memcpy.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000514 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000515}
516
Chad Rosiercc9030b2015-11-11 23:00:59 +0000517void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000518 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000519 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000520 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000521 for (Instruction &I : *BB) {
522 StoreInst *SI = dyn_cast<StoreInst>(&I);
523 if (!SI)
524 continue;
525
Chad Rosiera548fe52015-11-12 19:09:16 +0000526 // Make sure this is a strided store with a constant stride.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000527 switch (isLegalStore(SI)) {
528 case LegalStoreKind::None:
529 // Nothing to do
530 break;
531 case LegalStoreKind::Memset: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000532 // Find the base pointer.
533 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
534 StoreRefsForMemset[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000535 } break;
536 case LegalStoreKind::MemsetPattern: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000537 // Find the base pointer.
538 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
539 StoreRefsForMemsetPattern[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000540 } break;
541 case LegalStoreKind::Memcpy:
Anna Thomasb2a212c2017-06-06 16:45:25 +0000542 case LegalStoreKind::UnorderedAtomicMemcpy:
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000543 StoreRefsForMemcpy.push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000544 break;
545 default:
546 assert(false && "unhandled return value");
547 break;
548 }
Chad Rosiercc9030b2015-11-11 23:00:59 +0000549 }
550}
551
Chris Lattner8455b6e2011-01-02 19:01:03 +0000552/// runOnLoopBlock - Process the specified block, which lives in a counted loop
553/// with the specified backedge count. This block is known to be in the current
554/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000555bool LoopIdiomRecognize::runOnLoopBlock(
556 BasicBlock *BB, const SCEV *BECount,
557 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000558 // We can only promote stores in this block if they are unconditionally
559 // executed in the loop. For a block to be unconditionally executed, it has
560 // to dominate all the exit blocks of the loop. Verify this now.
561 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
562 if (!DT->dominates(BB, ExitBlocks[i]))
563 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000564
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000565 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000566 // Look for store instructions, which may be optimized to memset/memcpy.
567 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000568
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000569 // Look for a single store or sets of stores with a common base, which can be
570 // optimized into a memset (memset_pattern). The latter most commonly happens
571 // with structs and handunrolled loops.
572 for (auto &SL : StoreRefsForMemset)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000573 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000574
575 for (auto &SL : StoreRefsForMemsetPattern)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000576 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000577
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000578 // Optimize the store into a memcpy, if it feeds an similarly strided load.
579 for (auto &SI : StoreRefsForMemcpy)
580 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
581
Chandler Carruthbad690e2015-08-12 23:06:37 +0000582 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000583 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000584 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000585 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000586 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000587 if (!processLoopMemSet(MSI, BECount))
588 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000589 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000590
Chris Lattner86438102011-01-04 07:46:33 +0000591 // If processing the memset invalidated our iterator, start over from the
592 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000593 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000594 I = BB->begin();
595 continue;
596 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000597 }
Andrew Trick328b2232011-03-14 16:48:10 +0000598
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000599 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000600}
601
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000602/// See if this store(s) can be promoted to a memset.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000603bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000604 const SCEV *BECount, ForMemset For) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000605 // Try to find consecutive stores that can be transformed into memsets.
606 SetVector<StoreInst *> Heads, Tails;
607 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000608
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000609 // Do a quadratic search on all of the given stores and find
610 // all of the pairs of stores that follow each other.
611 SmallVector<unsigned, 16> IndexQueue;
612 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
613 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000614
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000615 Value *FirstStoredVal = SL[i]->getValueOperand();
616 Value *FirstStorePtr = SL[i]->getPointerOperand();
617 const SCEVAddRecExpr *FirstStoreEv =
618 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000619 APInt FirstStride = getStoreStride(FirstStoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000620 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
Chad Rosier79676142015-10-28 14:38:49 +0000621
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000622 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000623 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000624 Heads.insert(SL[i]);
625 continue;
626 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000627
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000628 Value *FirstSplatValue = nullptr;
629 Constant *FirstPatternValue = nullptr;
630
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000631 if (For == ForMemset::Yes)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000632 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000633 else
634 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
635
636 assert((FirstSplatValue || FirstPatternValue) &&
637 "Expected either splat value or pattern value.");
638
639 IndexQueue.clear();
640 // If a store has multiple consecutive store candidates, search Stores
641 // array according to the sequence: from i+1 to e, then from i-1 to 0.
642 // This is because usually pairing with immediate succeeding or preceding
643 // candidate create the best chance to find memset opportunity.
644 unsigned j = 0;
645 for (j = i + 1; j < e; ++j)
646 IndexQueue.push_back(j);
647 for (j = i; j > 0; --j)
648 IndexQueue.push_back(j - 1);
649
650 for (auto &k : IndexQueue) {
651 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
652 Value *SecondStorePtr = SL[k]->getPointerOperand();
653 const SCEVAddRecExpr *SecondStoreEv =
654 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000655 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000656
657 if (FirstStride != SecondStride)
658 continue;
659
660 Value *SecondStoredVal = SL[k]->getValueOperand();
661 Value *SecondSplatValue = nullptr;
662 Constant *SecondPatternValue = nullptr;
663
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000664 if (For == ForMemset::Yes)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000665 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000666 else
667 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
668
669 assert((SecondSplatValue || SecondPatternValue) &&
670 "Expected either splat value or pattern value.");
671
672 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000673 if (For == ForMemset::Yes) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000674 if (isa<UndefValue>(FirstSplatValue))
675 FirstSplatValue = SecondSplatValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000676 if (FirstSplatValue != SecondSplatValue)
677 continue;
678 } else {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000679 if (isa<UndefValue>(FirstPatternValue))
680 FirstPatternValue = SecondPatternValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000681 if (FirstPatternValue != SecondPatternValue)
682 continue;
683 }
684 Tails.insert(SL[k]);
685 Heads.insert(SL[i]);
686 ConsecutiveChain[SL[i]] = SL[k];
687 break;
688 }
689 }
690 }
691
692 // We may run into multiple chains that merge into a single chain. We mark the
693 // stores that we transformed so that we don't visit the same store twice.
694 SmallPtrSet<Value *, 16> TransformedStores;
695 bool Changed = false;
696
697 // For stores that start but don't end a link in the chain:
698 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
699 it != e; ++it) {
700 if (Tails.count(*it))
701 continue;
702
703 // We found a store instr that starts a chain. Now follow the chain and try
704 // to transform it.
705 SmallPtrSet<Instruction *, 8> AdjacentStores;
706 StoreInst *I = *it;
707
708 StoreInst *HeadStore = I;
709 unsigned StoreSize = 0;
710
711 // Collect the chain into a list.
712 while (Tails.count(I) || Heads.count(I)) {
713 if (TransformedStores.count(I))
714 break;
715 AdjacentStores.insert(I);
716
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000717 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000718 // Move to the next value in the chain.
719 I = ConsecutiveChain[I];
720 }
721
722 Value *StoredVal = HeadStore->getValueOperand();
723 Value *StorePtr = HeadStore->getPointerOperand();
724 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000725 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000726
727 // Check to see if the stride matches the size of the stores. If so, then
728 // we know that every byte is touched in the loop.
729 if (StoreSize != Stride && StoreSize != -Stride)
730 continue;
731
732 bool NegStride = StoreSize == -Stride;
733
734 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
735 StoredVal, HeadStore, AdjacentStores, StoreEv,
736 BECount, NegStride)) {
737 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
738 Changed = true;
739 }
740 }
741
742 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000743}
744
Chris Lattner86438102011-01-04 07:46:33 +0000745/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000746bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
747 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000748 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000749 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
750 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000751
Chris Lattnere6b261f2011-02-18 22:22:15 +0000752 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000753 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000754 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000755
Chris Lattner86438102011-01-04 07:46:33 +0000756 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000757
Chris Lattner86438102011-01-04 07:46:33 +0000758 // See if the pointer expression is an AddRec like {base,+,1} on the current
759 // loop, which indicates a strided store. If we have something else, it's a
760 // random store we can't handle.
761 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000763 return false;
764
765 // Reject memsets that are so large that they overflow an unsigned.
766 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
767 if ((SizeInBytes >> 32) != 0)
768 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000769
Chris Lattner86438102011-01-04 07:46:33 +0000770 // Check to see if the stride matches the size of the memset. If so, then we
771 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000772 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
773 if (!ConstStride)
774 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000775
Chad Rosier81362a82016-02-12 21:03:23 +0000776 APInt Stride = ConstStride->getAPInt();
777 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000778 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000779
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000780 // Verify that the memset value is loop invariant. If not, we can't promote
781 // the memset.
782 Value *SplatValue = MSI->getValue();
783 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
784 return false;
785
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000786 SmallPtrSet<Instruction *, 1> MSIs;
787 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000788 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000789 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Daniel Neilsonfb99a492018-02-08 17:33:08 +0000790 MSI->getDestAlignment(), SplatValue, MSI, MSIs,
791 Ev, BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000792}
793
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000794/// mayLoopAccessLocation - Return true if the specified loop might access the
795/// specified pointer location, which is a loop-strided access. The 'Access'
796/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000797static bool
798mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
799 const SCEV *BECount, unsigned StoreSize,
800 AliasAnalysis &AA,
801 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000802 // Get the location that may be stored across the loop. Since the access is
803 // strided positively through memory, we say that the modified location starts
804 // at the pointer and has infinite size.
George Burgess IV7e128752018-12-24 05:55:50 +0000805 LocationSize AccessSize = LocationSize::unknown();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000806
807 // If the loop iterates a fixed number of times, we can refine the access size
808 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
809 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
George Burgess IV7e128752018-12-24 05:55:50 +0000810 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
811 StoreSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000812
813 // TODO: For this to be really effective, we have to dive into the pointer
814 // operand in the store. Store to &A[i] of 100 will always return may alias
815 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
816 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000817 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000818
819 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
820 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000821 for (Instruction &I : **BI)
822 if (IgnoredStores.count(&I) == 0 &&
Alina Sbirlea18fea012017-12-06 19:56:37 +0000823 isModOrRefSet(
824 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000825 return true;
826
827 return false;
828}
829
Chad Rosiered0c7d12015-11-13 19:11:07 +0000830// If we have a negative stride, Start refers to the end of the memory location
831// we're trying to memset. Therefore, we need to recompute the base pointer,
832// which is just Start - BECount*Size.
833static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
834 Type *IntPtr, unsigned StoreSize,
835 ScalarEvolution *SE) {
836 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
837 if (StoreSize != 1)
838 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
839 SCEV::FlagNUW);
840 return SE->getMinusSCEV(Start, Index);
841}
842
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000843/// Compute the number of bytes as a SCEV from the backedge taken count.
844///
845/// This also maps the SCEV into the provided type and tries to handle the
846/// computation in a way that will fold cleanly.
847static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
848 unsigned StoreSize, Loop *CurLoop,
849 const DataLayout *DL, ScalarEvolution *SE) {
850 const SCEV *NumBytesS;
851 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
852 // pointer size if it isn't already.
853 //
854 // If we're going to need to zero extend the BE count, check if we can add
855 // one to it prior to zero extending without overflow. Provided this is safe,
856 // it allows better simplification of the +1.
857 if (DL->getTypeSizeInBits(BECount->getType()) <
858 DL->getTypeSizeInBits(IntPtr) &&
859 SE->isLoopEntryGuardedByCond(
860 CurLoop, ICmpInst::ICMP_NE, BECount,
861 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
862 NumBytesS = SE->getZeroExtendExpr(
863 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
864 IntPtr);
865 } else {
866 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
867 SE->getOne(IntPtr), SCEV::FlagNUW);
868 }
869
870 // And scale it based on the store size.
871 if (StoreSize != 1) {
872 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
873 SCEV::FlagNUW);
874 }
875 return NumBytesS;
876}
877
Chris Lattner0f4a6402011-02-19 19:31:39 +0000878/// processLoopStridedStore - We see a strided store of some value. If we can
879/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000880bool LoopIdiomRecognize::processLoopStridedStore(
881 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000882 Value *StoredVal, Instruction *TheStore,
883 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000884 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000885 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
Craig Topperf40110f2014-04-25 05:29:35 +0000886 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000887
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000888 if (!SplatValue)
889 PatternValue = getMemSetPatternValue(StoredVal, DL);
890
891 assert((SplatValue || PatternValue) &&
892 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000893
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000894 // The trip count of the loop and the base pointer of the addrec SCEV is
895 // guaranteed to be loop invariant, which means that it should dominate the
896 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000897 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000898 BasicBlock *Preheader = CurLoop->getLoopPreheader();
899 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000900 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000901
Matt Arsenault009faed2013-09-11 05:09:42 +0000902 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000903 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000904
905 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000906 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000907 if (NegStride)
908 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000909
Aditya Kumar1c42d132017-05-05 14:49:45 +0000910 // TODO: ideally we should still be able to generate memset if SCEV expander
911 // is taught to generate the dependencies at the latest point.
912 if (!isSafeToExpand(Start, *SE))
913 return false;
914
Chris Lattner29e14ed2010-12-26 23:42:51 +0000915 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000916 // this into a memset in the loop preheader now if we want. However, this
917 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000918 // or write to the aliased location. Check for any overlap by generating the
919 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000920 Value *BasePtr =
921 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Alina Sbirlea193429f2017-12-07 22:41:34 +0000922 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
923 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000924 Expander.clear();
925 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000926 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000927 return false;
928 }
929
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000930 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
931 return false;
932
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000933 // Okay, everything looks good, insert the memset.
934
Chandler Carruthbad690e2015-08-12 23:06:37 +0000935 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000936 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
Andrew Trick328b2232011-03-14 16:48:10 +0000937
Aditya Kumar1c42d132017-05-05 14:49:45 +0000938 // TODO: ideally we should still be able to generate memset if SCEV expander
939 // is taught to generate the dependencies at the latest point.
940 if (!isSafeToExpand(NumBytesS, *SE))
941 return false;
942
Andrew Trick328b2232011-03-14 16:48:10 +0000943 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000944 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000945
Devang Pateld00c6282011-03-07 22:43:45 +0000946 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000947 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000948 NewCall =
949 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000950 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000951 // Everything is emitted in default address space
952 Type *Int8PtrTy = DestInt8PtrTy;
953
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000954 Module *M = TheStore->getModule();
David Bolvansky7c7760d2018-10-16 21:18:31 +0000955 StringRef FuncName = "memset_pattern16";
James Y Knight13680222019-02-01 02:28:03 +0000956 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
957 Int8PtrTy, Int8PtrTy, IntPtr);
David Bolvansky7c7760d2018-10-16 21:18:31 +0000958 inferLibFuncAttributes(M, FuncName, *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000959
Chris Lattner0f4a6402011-02-19 19:31:39 +0000960 // Otherwise we should form a memset_pattern16. PatternValue is known to be
961 // an constant array of 16-bytes. Plop the value into a mergable global.
962 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000963 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000964 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000965 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Guillaume Chatelet0e620112019-10-15 11:24:36 +0000966 GV->setAlignment(Align(16));
Matt Arsenault009faed2013-09-11 05:09:42 +0000967 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000968 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000969 }
Andrew Trick328b2232011-03-14 16:48:10 +0000970
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000971 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
972 << " from store to: " << *Ev << " at: " << *TheStore
973 << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000974 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000975
Roman Lebedeve8578952019-05-30 13:02:06 +0000976 ORE.emit([&]() {
977 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStridedStore",
978 NewCall->getDebugLoc(), Preheader)
979 << "Transformed loop-strided store into a call to "
980 << ore::NV("NewFunction", NewCall->getCalledFunction())
981 << "() function";
982 });
983
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000984 // Okay, the memset has been formed. Zap the original store and anything that
985 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000986 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000987 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000988 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000989 return true;
990}
991
Chad Rosier1cd3da12015-11-19 21:33:07 +0000992/// If the stored value is a strided load in the same loop with the same stride
993/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000994/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000995bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
996 const SCEV *BECount) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000997 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000998
999 Value *StorePtr = SI->getPointerOperand();
1000 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +00001001 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001002 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +00001003 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +00001004
Chad Rosierfddc01f2015-11-19 18:22:21 +00001005 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +00001006 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +00001007 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
Chad Rosierfddc01f2015-11-19 18:22:21 +00001008
1009 // See if the pointer expression is an AddRec like {base,+,1} on the current
1010 // loop, which indicates a strided load. If we have something else, it's a
1011 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +00001012 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +00001013 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +00001014
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001015 // The trip count of the loop and the base pointer of the addrec SCEV is
1016 // guaranteed to be loop invariant, which means that it should dominate the
1017 // header. This allows us to insert code for it in the preheader.
1018 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1019 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +00001020 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001021
Chad Rosiercc299b62015-11-13 21:51:02 +00001022 const SCEV *StrStart = StoreEv->getStart();
1023 unsigned StrAS = SI->getPointerAddressSpace();
1024 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
1025
1026 // Handle negative strided loops.
1027 if (NegStride)
1028 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
1029
Chris Lattner85b6d812011-01-02 03:37:56 +00001030 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001031 // this into a memcpy in the loop preheader now if we want. However, this
1032 // would be unsafe to do if there is anything else in the loop that may read
1033 // or write the memory region we're storing to. This includes the load that
1034 // feeds the stores. Check for an alias by generating the base address and
1035 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001036 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001037 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001038
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001039 SmallPtrSet<Instruction *, 1> Stores;
1040 Stores.insert(SI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00001041 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001042 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001043 Expander.clear();
1044 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001045 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001046 return false;
1047 }
1048
Chad Rosiercc299b62015-11-13 21:51:02 +00001049 const SCEV *LdStart = LoadEv->getStart();
1050 unsigned LdAS = LI->getPointerAddressSpace();
1051
1052 // Handle negative strided loops.
1053 if (NegStride)
1054 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
1055
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001056 // For a memcpy, we have to make sure that the input array is not being
1057 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001058 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001059 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001060
Alina Sbirlea193429f2017-12-07 22:41:34 +00001061 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1062 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001063 Expander.clear();
1064 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001065 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1066 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001067 return false;
1068 }
1069
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001070 if (avoidLIRForMultiBlockLoop())
1071 return false;
1072
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001073 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001074
Chandler Carruthbad690e2015-08-12 23:06:37 +00001075 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +00001076 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001077
1078 Value *NumBytes =
1079 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1080
Anna Thomasb2a212c2017-06-06 16:45:25 +00001081 CallInst *NewCall = nullptr;
1082 // Check whether to generate an unordered atomic memcpy:
Hiroshi Inouef2096492018-06-14 05:41:49 +00001083 // If the load or store are atomic, then they must necessarily be unordered
Anna Thomasb2a212c2017-06-06 16:45:25 +00001084 // by previous checks.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001085 if (!SI->isAtomic() && !LI->isAtomic())
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001086 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlignment(),
1087 LoadBasePtr, LI->getAlignment(), NumBytes);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001088 else {
Anna Thomasb2a212c2017-06-06 16:45:25 +00001089 // We cannot allow unaligned ops for unordered load/store, so reject
1090 // anything where the alignment isn't at least the element size.
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001091 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
Anna Thomasb2a212c2017-06-06 16:45:25 +00001092 if (Align < StoreSize)
1093 return false;
1094
1095 // If the element.atomic memcpy is not lowered into explicit
1096 // loads/stores later, then it will be lowered into an element-size
1097 // specific lib call. If the lib call doesn't exist for our store size, then
1098 // we shouldn't generate the memcpy.
1099 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1100 return false;
1101
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001102 // Create the call.
1103 // Note that unordered atomic loads/stores are *required* by the spec to
1104 // have an alignment but non-atomic loads/stores may not.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001105 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001106 StoreBasePtr, SI->getAlignment(), LoadBasePtr, LI->getAlignment(),
1107 NumBytes, StoreSize);
Anna Thomasb2a212c2017-06-06 16:45:25 +00001108 }
Devang Patel0daa07e2011-05-04 21:37:05 +00001109 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001110
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001111 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1112 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1113 << " from store ptr=" << *StoreEv << " at: " << *SI
1114 << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001115
Roman Lebedeve8578952019-05-30 13:02:06 +00001116 ORE.emit([&]() {
1117 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1118 NewCall->getDebugLoc(), Preheader)
1119 << "Formed a call to "
1120 << ore::NV("NewFunction", NewCall->getCalledFunction())
1121 << "() function";
1122 });
1123
Chad Rosier7f08d802015-10-13 20:59:16 +00001124 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +00001125 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +00001126 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001127 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001128 return true;
1129}
Chandler Carruthd9c60702015-08-13 00:10:03 +00001130
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001131// When compiling for codesize we avoid idiom recognition for a multi-block loop
1132// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1133//
1134bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1135 bool IsLoopMemset) {
1136 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1137 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001138 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1139 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1140 << " avoided: multi-block top-level loop\n");
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001141 return true;
1142 }
1143 }
1144
1145 return false;
1146}
1147
Chandler Carruthd9c60702015-08-13 00:10:03 +00001148bool LoopIdiomRecognize::runOnNoncountableLoop() {
Roman Lebedev95dec502019-05-29 20:11:53 +00001149 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1150 << CurLoop->getHeader()->getParent()->getName()
1151 << "] Noncountable Loop %"
1152 << CurLoop->getHeader()->getName() << "\n");
1153
Roman Lebedevc4b757b2019-11-02 12:39:02 +03001154 return recognizePopcount() || recognizeAndInsertFFS();
Chandler Carruthd9c60702015-08-13 00:10:03 +00001155}
Chandler Carruth8219a502015-08-13 00:44:29 +00001156
1157/// Check if the given conditional branch is based on the comparison between
Craig Topperc9a60002018-12-26 21:59:48 +00001158/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1159/// true), the control yields to the loop entry. If the branch matches the
1160/// behavior, the variable involved in the comparison is returned. This function
1161/// will be called to see if the precondition and postcondition of the loop are
1162/// in desirable form.
1163static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1164 bool JmpOnZero = false) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001165 if (!BI || !BI->isConditional())
1166 return nullptr;
1167
1168 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1169 if (!Cond)
1170 return nullptr;
1171
1172 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1173 if (!CmpZero || !CmpZero->isZero())
1174 return nullptr;
1175
Craig Topperc9a60002018-12-26 21:59:48 +00001176 BasicBlock *TrueSucc = BI->getSuccessor(0);
1177 BasicBlock *FalseSucc = BI->getSuccessor(1);
1178 if (JmpOnZero)
1179 std::swap(TrueSucc, FalseSucc);
1180
Chandler Carruth8219a502015-08-13 00:44:29 +00001181 ICmpInst::Predicate Pred = Cond->getPredicate();
Craig Topperc9a60002018-12-26 21:59:48 +00001182 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1183 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
Chandler Carruth8219a502015-08-13 00:44:29 +00001184 return Cond->getOperand(0);
1185
1186 return nullptr;
1187}
1188
Davide Italiano4bc91192017-05-23 22:32:56 +00001189// Check if the recurrence variable `VarX` is in the right form to create
1190// the idiom. Returns the value coerced to a PHINode if so.
1191static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1192 BasicBlock *LoopEntry) {
1193 auto *PhiX = dyn_cast<PHINode>(VarX);
1194 if (PhiX && PhiX->getParent() == LoopEntry &&
1195 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1196 return PhiX;
1197 return nullptr;
1198}
1199
Chandler Carruth8219a502015-08-13 00:44:29 +00001200/// Return true iff the idiom is detected in the loop.
1201///
1202/// Additionally:
1203/// 1) \p CntInst is set to the instruction counting the population bit.
1204/// 2) \p CntPhi is set to the corresponding phi node.
1205/// 3) \p Var is set to the value whose population bits are being counted.
1206///
1207/// The core idiom we are trying to detect is:
1208/// \code
1209/// if (x0 != 0)
1210/// goto loop-exit // the precondition of the loop
1211/// cnt0 = init-val;
1212/// do {
1213/// x1 = phi (x0, x2);
1214/// cnt1 = phi(cnt0, cnt2);
1215///
1216/// cnt2 = cnt1 + 1;
1217/// ...
1218/// x2 = x1 & (x1 - 1);
1219/// ...
1220/// } while(x != 0);
1221///
1222/// loop-exit:
1223/// \endcode
1224static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1225 Instruction *&CntInst, PHINode *&CntPhi,
1226 Value *&Var) {
1227 // step 1: Check to see if the look-back branch match this pattern:
1228 // "if (a!=0) goto loop-entry".
1229 BasicBlock *LoopEntry;
1230 Instruction *DefX2, *CountInst;
1231 Value *VarX1, *VarX0;
1232 PHINode *PhiX, *CountPhi;
1233
1234 DefX2 = CountInst = nullptr;
1235 VarX1 = VarX0 = nullptr;
1236 PhiX = CountPhi = nullptr;
1237 LoopEntry = *(CurLoop->block_begin());
1238
1239 // step 1: Check if the loop-back branch is in desirable form.
1240 {
1241 if (Value *T = matchCondition(
1242 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1243 DefX2 = dyn_cast<Instruction>(T);
1244 else
1245 return false;
1246 }
1247
1248 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1249 {
1250 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1251 return false;
1252
1253 BinaryOperator *SubOneOp;
1254
1255 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1256 VarX1 = DefX2->getOperand(1);
1257 else {
1258 VarX1 = DefX2->getOperand(0);
1259 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1260 }
Craig Topper856fd682018-05-03 05:48:49 +00001261 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001262 return false;
1263
Craig Topper8ef2abd2018-05-03 05:00:18 +00001264 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
Chandler Carruth8219a502015-08-13 00:44:29 +00001265 if (!Dec ||
Craig Topper8ef2abd2018-05-03 05:00:18 +00001266 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1267 (SubOneOp->getOpcode() == Instruction::Add &&
Craig Topper79ab6432017-07-06 18:39:47 +00001268 Dec->isMinusOne()))) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001269 return false;
1270 }
1271 }
1272
1273 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001274 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1275 if (!PhiX)
1276 return false;
Chandler Carruth8219a502015-08-13 00:44:29 +00001277
1278 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1279 {
1280 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001281 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001282 IterE = LoopEntry->end();
1283 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001284 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001285 if (Inst->getOpcode() != Instruction::Add)
1286 continue;
1287
1288 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1289 if (!Inc || !Inc->isOne())
1290 continue;
1291
Davide Italiano7bf95b92017-05-23 23:51:54 +00001292 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1293 if (!Phi)
Chandler Carruth8219a502015-08-13 00:44:29 +00001294 continue;
1295
1296 // Check if the result of the instruction is live of the loop.
1297 bool LiveOutLoop = false;
1298 for (User *U : Inst->users()) {
1299 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1300 LiveOutLoop = true;
1301 break;
1302 }
1303 }
1304
1305 if (LiveOutLoop) {
1306 CountInst = Inst;
1307 CountPhi = Phi;
1308 break;
1309 }
1310 }
1311
1312 if (!CountInst)
1313 return false;
1314 }
1315
1316 // step 5: check if the precondition is in this form:
1317 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1318 {
1319 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1320 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1321 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1322 return false;
1323
1324 CntInst = CountInst;
1325 CntPhi = CountPhi;
1326 Var = T;
1327 }
1328
1329 return true;
1330}
1331
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001332/// Return true if the idiom is detected in the loop.
1333///
1334/// Additionally:
1335/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1336/// or nullptr if there is no such.
1337/// 2) \p CntPhi is set to the corresponding phi node
1338/// or nullptr if there is no such.
1339/// 3) \p Var is set to the value whose CTLZ could be used.
1340/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1341///
1342/// The core idiom we are trying to detect is:
1343/// \code
1344/// if (x0 == 0)
1345/// goto loop-exit // the precondition of the loop
1346/// cnt0 = init-val;
1347/// do {
1348/// x = phi (x0, x.next); //PhiX
1349/// cnt = phi(cnt0, cnt.next);
1350///
1351/// cnt.next = cnt + 1;
1352/// ...
1353/// x.next = x >> 1; // DefX
1354/// ...
1355/// } while(x.next != 0);
1356///
1357/// loop-exit:
1358/// \endcode
Craig Topperc9a60002018-12-26 21:59:48 +00001359static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1360 Intrinsic::ID &IntrinID, Value *&InitX,
1361 Instruction *&CntInst, PHINode *&CntPhi,
1362 Instruction *&DefX) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001363 BasicBlock *LoopEntry;
1364 Value *VarX = nullptr;
1365
1366 DefX = nullptr;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001367 CntInst = nullptr;
1368 CntPhi = nullptr;
1369 LoopEntry = *(CurLoop->block_begin());
1370
1371 // step 1: Check if the loop-back branch is in desirable form.
1372 if (Value *T = matchCondition(
1373 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1374 DefX = dyn_cast<Instruction>(T);
1375 else
1376 return false;
1377
Craig Topperc9a60002018-12-26 21:59:48 +00001378 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1379 if (!DefX || !DefX->isShift())
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001380 return false;
Craig Topperc9a60002018-12-26 21:59:48 +00001381 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1382 Intrinsic::ctlz;
Evgeny Stupachenkod699de22017-11-03 18:50:03 +00001383 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1384 if (!Shft || !Shft->isOne())
1385 return false;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001386 VarX = DefX->getOperand(0);
1387
1388 // step 3: Check the recurrence of variable X
Craig Topperc9a60002018-12-26 21:59:48 +00001389 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
Davide Italiano4bc91192017-05-23 22:32:56 +00001390 if (!PhiX)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001391 return false;
1392
Craig Topperc9a60002018-12-26 21:59:48 +00001393 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1394
1395 // Make sure the initial value can't be negative otherwise the ashr in the
1396 // loop might never reach zero which would make the loop infinite.
1397 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1398 return false;
1399
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001400 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1401 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1402 // then all uses of "cnt.next" could be optimized to the trip count
1403 // plus "cnt0". Currently it is not optimized.
1404 // This step could be used to detect POPCNT instruction:
1405 // cnt.next = cnt + (x.next & 1)
1406 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1407 IterE = LoopEntry->end();
1408 Iter != IterE; Iter++) {
1409 Instruction *Inst = &*Iter;
1410 if (Inst->getOpcode() != Instruction::Add)
1411 continue;
1412
1413 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1414 if (!Inc || !Inc->isOne())
1415 continue;
1416
Davide Italiano7bf95b92017-05-23 23:51:54 +00001417 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1418 if (!Phi)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001419 continue;
1420
1421 CntInst = Inst;
1422 CntPhi = Phi;
1423 break;
1424 }
1425 if (!CntInst)
1426 return false;
1427
1428 return true;
1429}
1430
Craig Topperc9a60002018-12-26 21:59:48 +00001431/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1432/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1433/// trip count returns true; otherwise, returns false.
1434bool LoopIdiomRecognize::recognizeAndInsertFFS() {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001435 // Give up if the loop has multiple blocks or multiple backedges.
1436 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1437 return false;
1438
Craig Topperc9a60002018-12-26 21:59:48 +00001439 Intrinsic::ID IntrinID;
1440 Value *InitX;
1441 Instruction *DefX = nullptr;
1442 PHINode *CntPhi = nullptr;
1443 Instruction *CntInst = nullptr;
1444 // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1445 // this is always 6.
1446 size_t IdiomCanonicalSize = 6;
1447
1448 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1449 CntInst, CntPhi, DefX))
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001450 return false;
1451
1452 bool IsCntPhiUsedOutsideLoop = false;
1453 for (User *U : CntPhi->users())
Craig Topper83042312018-05-04 01:04:24 +00001454 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001455 IsCntPhiUsedOutsideLoop = true;
1456 break;
1457 }
1458 bool IsCntInstUsedOutsideLoop = false;
1459 for (User *U : CntInst->users())
Craig Topper83042312018-05-04 01:04:24 +00001460 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001461 IsCntInstUsedOutsideLoop = true;
1462 break;
1463 }
1464 // If both CntInst and CntPhi are used outside the loop the profitability
1465 // is questionable.
1466 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1467 return false;
1468
1469 // For some CPUs result of CTLZ(X) intrinsic is undefined
1470 // when X is 0. If we can not guarantee X != 0, we need to check this
1471 // when expand.
1472 bool ZeroCheck = false;
1473 // It is safe to assume Preheader exist as it was checked in
1474 // parent function RunOnLoop.
1475 BasicBlock *PH = CurLoop->getLoopPreheader();
Craig Topper9a6c0bd2018-05-31 22:16:55 +00001476
Craig Toppered6acde2018-07-11 22:35:28 +00001477 // If we are using the count instruction outside the loop, make sure we
1478 // have a zero check as a precondition. Without the check the loop would run
1479 // one iteration for before any check of the input value. This means 0 and 1
1480 // would have identical behavior in the original loop and thus
1481 if (!IsCntPhiUsedOutsideLoop) {
1482 auto *PreCondBB = PH->getSinglePredecessor();
1483 if (!PreCondBB)
1484 return false;
1485 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1486 if (!PreCondBI)
1487 return false;
1488 if (matchCondition(PreCondBI, PH) != InitX)
1489 return false;
1490 ZeroCheck = true;
1491 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001492
Craig Topperc9a60002018-12-26 21:59:48 +00001493 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1494 // profitable if we delete the loop.
1495
1496 // the loop has only 6 instructions:
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001497 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1498 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1499 // %shr = ashr %n.addr.0, 1
1500 // %tobool = icmp eq %shr, 0
1501 // %inc = add nsw %i.0, 1
1502 // br i1 %tobool
1503
Craig Toppercafae622018-05-04 01:04:26 +00001504 const Value *Args[] =
Craig Topperded8ee02018-05-04 17:39:08 +00001505 {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext())
1506 : ConstantInt::getFalse(InitX->getContext())};
Davide Italiano73929c42019-02-03 20:33:20 +00001507
1508 // @llvm.dbg doesn't count as they have no semantic effect.
1509 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1510 uint32_t HeaderSize =
1511 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1512
1513 if (HeaderSize != IdiomCanonicalSize &&
Craig Topperc9a60002018-12-26 21:59:48 +00001514 TTI->getIntrinsicCost(IntrinID, InitX->getType(), Args) >
Davide Italiano73929c42019-02-03 20:33:20 +00001515 TargetTransformInfo::TCC_Basic)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001516 return false;
1517
Craig Topperc9a60002018-12-26 21:59:48 +00001518 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
Craig Topper28352782018-07-08 01:45:47 +00001519 DefX->getDebugLoc(), ZeroCheck,
1520 IsCntPhiUsedOutsideLoop);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001521 return true;
1522}
1523
Chandler Carruth8219a502015-08-13 00:44:29 +00001524/// Recognizes a population count idiom in a non-countable loop.
1525///
1526/// If detected, transforms the relevant code to issue the popcount intrinsic
1527/// function call, and returns true; otherwise, returns false.
1528bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001529 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1530 return false;
1531
1532 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001533 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001534 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1535 // in a compact loop.
1536
Renato Golin655348f2015-08-13 11:25:38 +00001537 // Give up if the loop has multiple blocks or multiple backedges.
1538 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001539 return false;
1540
Renato Golin655348f2015-08-13 11:25:38 +00001541 BasicBlock *LoopBody = *(CurLoop->block_begin());
1542 if (LoopBody->size() >= 20) {
1543 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001544 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001545 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001546
1547 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001548 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001549 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001550 return false;
1551 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001552 if (!EntryBI || EntryBI->isConditional())
1553 return false;
1554
Hiroshi Inouef2096492018-06-14 05:41:49 +00001555 // It should have a precondition block where the generated popcount intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001556 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001557 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001558 if (!PreCondBB)
1559 return false;
1560 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1561 if (!PreCondBI || PreCondBI->isUnconditional())
1562 return false;
1563
1564 Instruction *CntInst;
1565 PHINode *CntPhi;
1566 Value *Val;
1567 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1568 return false;
1569
1570 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1571 return true;
1572}
1573
1574static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001575 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001576 Value *Ops[] = {Val};
1577 Type *Tys[] = {Val->getType()};
1578
1579 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001580 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
Chandler Carruth8219a502015-08-13 00:44:29 +00001581 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1582 CI->setDebugLoc(DL);
1583
1584 return CI;
1585}
1586
Craig Topperc9a60002018-12-26 21:59:48 +00001587static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1588 const DebugLoc &DL, bool ZeroCheck,
1589 Intrinsic::ID IID) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001590 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1591 Type *Tys[] = {Val->getType()};
1592
1593 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001594 Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001595 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1596 CI->setDebugLoc(DL);
1597
1598 return CI;
1599}
1600
Craig Topperc9a60002018-12-26 21:59:48 +00001601/// Transform the following loop (Using CTLZ, CTTZ is similar):
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001602/// loop:
1603/// CntPhi = PHI [Cnt0, CntInst]
1604/// PhiX = PHI [InitX, DefX]
1605/// CntInst = CntPhi + 1
1606/// DefX = PhiX >> 1
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001607/// LOOP_BODY
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001608/// Br: loop if (DefX != 0)
1609/// Use(CntPhi) or Use(CntInst)
1610///
1611/// Into:
1612/// If CntPhi used outside the loop:
1613/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1614/// Count = CountPrev + 1
1615/// else
1616/// Count = BitWidth(InitX) - CTLZ(InitX)
1617/// loop:
1618/// CntPhi = PHI [Cnt0, CntInst]
1619/// PhiX = PHI [InitX, DefX]
1620/// PhiCount = PHI [Count, Dec]
1621/// CntInst = CntPhi + 1
1622/// DefX = PhiX >> 1
1623/// Dec = PhiCount - 1
1624/// LOOP_BODY
1625/// Br: loop if (Dec != 0)
1626/// Use(CountPrev + Cnt0) // Use(CntPhi)
1627/// or
1628/// Use(Count + Cnt0) // Use(CntInst)
1629///
1630/// If LOOP_BODY is empty the loop will be deleted.
1631/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1632void LoopIdiomRecognize::transformLoopToCountable(
Craig Topperc9a60002018-12-26 21:59:48 +00001633 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
1634 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
1635 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
Craig Topper9510f702018-05-04 01:04:28 +00001636 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001637
Craig Topperc9a60002018-12-26 21:59:48 +00001638 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
1639 IRBuilder<> Builder(PreheaderBr);
1640 Builder.SetCurrentDebugLocation(DL);
1641 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext;
1642
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001643 // Count = BitWidth - CTLZ(InitX);
1644 // If there are uses of CntPhi create:
1645 // CountPrev = BitWidth - CTLZ(InitX >> 1);
Craig Topper28352782018-07-08 01:45:47 +00001646 if (IsCntPhiUsedOutsideLoop) {
1647 if (DefX->getOpcode() == Instruction::AShr)
1648 InitXNext =
1649 Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1));
1650 else if (DefX->getOpcode() == Instruction::LShr)
1651 InitXNext =
1652 Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topperc9a60002018-12-26 21:59:48 +00001653 else if (DefX->getOpcode() == Instruction::Shl) // cttz
1654 InitXNext =
1655 Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topper28352782018-07-08 01:45:47 +00001656 else
Fangrui Songf78650a2018-07-30 19:41:25 +00001657 llvm_unreachable("Unexpected opcode!");
Craig Topper28352782018-07-08 01:45:47 +00001658 } else
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001659 InitXNext = InitX;
Craig Topperc9a60002018-12-26 21:59:48 +00001660 FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001661 Count = Builder.CreateSub(
Craig Topperc9a60002018-12-26 21:59:48 +00001662 ConstantInt::get(FFS->getType(),
1663 FFS->getType()->getIntegerBitWidth()),
1664 FFS);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001665 if (IsCntPhiUsedOutsideLoop) {
1666 CountPrev = Count;
1667 Count = Builder.CreateAdd(
1668 CountPrev,
1669 ConstantInt::get(CountPrev->getType(), 1));
1670 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001671
Craig Topperc9a60002018-12-26 21:59:48 +00001672 NewCount = Builder.CreateZExtOrTrunc(
1673 IsCntPhiUsedOutsideLoop ? CountPrev : Count,
1674 cast<IntegerType>(CntInst->getType()));
1675
1676 // If the counter's initial value is not zero, insert Add Inst.
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001677 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1678 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1679 if (!InitConst || !InitConst->isZero())
1680 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1681
1682 // Step 2: Insert new IV and loop condition:
1683 // loop:
1684 // ...
1685 // PhiCount = PHI [Count, Dec]
1686 // ...
1687 // Dec = PhiCount - 1
1688 // ...
1689 // Br: loop if (Dec != 0)
1690 BasicBlock *Body = *(CurLoop->block_begin());
Craig Topper9510f702018-05-04 01:04:28 +00001691 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001692 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1693 Type *Ty = Count->getType();
1694
1695 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1696
1697 Builder.SetInsertPoint(LbCond);
1698 Instruction *TcDec = cast<Instruction>(
1699 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1700 "tcdec", false, true));
1701
1702 TcPhi->addIncoming(Count, Preheader);
1703 TcPhi->addIncoming(TcDec, Body);
1704
1705 CmpInst::Predicate Pred =
1706 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1707 LbCond->setPredicate(Pred);
1708 LbCond->setOperand(0, TcDec);
1709 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1710
1711 // Step 3: All the references to the original counter outside
Craig Topperc9a60002018-12-26 21:59:48 +00001712 // the loop are replaced with the NewCount
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001713 if (IsCntPhiUsedOutsideLoop)
1714 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1715 else
1716 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1717
1718 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1719 // loop. The loop would otherwise not be deleted even if it becomes empty.
1720 SE->forgetLoop(CurLoop);
1721}
1722
Chandler Carruth8219a502015-08-13 00:44:29 +00001723void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1724 Instruction *CntInst,
1725 PHINode *CntPhi, Value *Var) {
1726 BasicBlock *PreHead = CurLoop->getLoopPreheader();
Craig Topper9510f702018-05-04 01:04:28 +00001727 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
Craig Topper27847862018-06-25 20:45:45 +00001728 const DebugLoc &DL = CntInst->getDebugLoc();
Chandler Carruth8219a502015-08-13 00:44:29 +00001729
1730 // Assuming before transformation, the loop is following:
1731 // if (x) // the precondition
1732 // do { cnt++; x &= x - 1; } while(x);
1733
1734 // Step 1: Insert the ctpop instruction at the end of the precondition block
1735 IRBuilder<> Builder(PreCondBr);
1736 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1737 {
1738 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1739 NewCount = PopCntZext =
1740 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1741
1742 if (NewCount != PopCnt)
1743 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1744
1745 // TripCnt is exactly the number of iterations the loop has
1746 TripCnt = NewCount;
1747
1748 // If the population counter's initial value is not zero, insert Add Inst.
1749 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1750 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1751 if (!InitConst || !InitConst->isZero()) {
1752 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1753 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1754 }
1755 }
1756
Nick Lewycky2c852542015-08-19 06:22:33 +00001757 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001758 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001759 // function would be partial dead code, and downstream passes will drag
1760 // it back from the precondition block to the preheader.
1761 {
1762 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1763
1764 Value *Opnd0 = PopCntZext;
1765 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1766 if (PreCond->getOperand(0) != Var)
1767 std::swap(Opnd0, Opnd1);
1768
1769 ICmpInst *NewPreCond = cast<ICmpInst>(
1770 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1771 PreCondBr->setCondition(NewPreCond);
1772
1773 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1774 }
1775
1776 // Step 3: Note that the population count is exactly the trip count of the
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001777 // loop in question, which enable us to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001778 // loop into a countable one. The benefit is twofold:
1779 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001780 // - If the loop only counts population, the entire loop becomes dead after
1781 // the transformation. It is a lot easier to prove a countable loop dead
1782 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001783 // isn't dead even if it computes nothing useful. In general, DCE needs
1784 // to prove a noncountable loop finite before safely delete it.)
1785 //
1786 // - If the loop also performs something else, it remains alive.
1787 // Since it is transformed to countable form, it can be aggressively
1788 // optimized by some optimizations which are in general not applicable
1789 // to a noncountable loop.
1790 //
1791 // After this step, this loop (conceptually) would look like following:
1792 // newcnt = __builtin_ctpop(x);
1793 // t = newcnt;
1794 // if (x)
1795 // do { cnt++; x &= x-1; t--) } while (t > 0);
1796 BasicBlock *Body = *(CurLoop->block_begin());
1797 {
Craig Topper9510f702018-05-04 01:04:28 +00001798 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001799 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1800 Type *Ty = TripCnt->getType();
1801
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001802 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001803
1804 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001805 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001806 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1807 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001808
1809 TcPhi->addIncoming(TripCnt, PreHead);
1810 TcPhi->addIncoming(TcDec, Body);
1811
1812 CmpInst::Predicate Pred =
1813 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1814 LbCond->setPredicate(Pred);
1815 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001816 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001817 }
1818
1819 // Step 4: All the references to the original population counter outside
1820 // the loop are replaced with the NewCount -- the value returned from
1821 // __builtin_ctpop().
1822 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1823
1824 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1825 // loop. The loop would otherwise not be deleted even if it becomes empty.
1826 SE->forgetLoop(CurLoop);
1827}