1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form. In cases that this kicks in, it can be a significant
14 // If compiling for code size we avoid idiom recognition if the resulting
15 // code could be larger than the code for the original loop. One way this could
16 // happen is if the loop is not removable after idiom recognition due to the
17 // presence of non-idiom instructions. The initial implementation of the
18 // heuristics applies to idioms in multi-block loops.
20 //===----------------------------------------------------------------------===//
24 // Future loop memory idioms to recognize:
25 // memcmp, memmove, strlen, etc.
26 // Future floating point idioms to recognize in -ffast-math mode:
28 // Future integer operation idioms to recognize:
31 // Beware that isel's default lowering for ctpop is highly inefficient for
32 // i64 and larger types when i64 is legal and the value has few bits set. It
33 // would be good to enhance isel to emit a loop for ctpop in this case.
35 // This could recognize common matrix multiplies and dot product idioms and
36 // replace them with calls to BLAS (if linked in??).
38 //===----------------------------------------------------------------------===//
40 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SetVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Analysis/AliasAnalysis.h"
45 #include "llvm/Analysis/BasicAliasAnalysis.h"
46 #include "llvm/Analysis/GlobalsModRef.h"
47 #include "llvm/Analysis/LoopAccessAnalysis.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
50 #include "llvm/Analysis/ScalarEvolutionExpander.h"
51 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/TargetTransformInfo.h"
54 #include "llvm/Analysis/ValueTracking.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include "llvm/Transforms/Scalar/LoopPassManager.h"
64 #include "llvm/Transforms/Utils/BuildLibCalls.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include "llvm/Transforms/Utils/LoopUtils.h"
69 #define DEBUG_TYPE "loop-idiom"
71 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
72 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
74 static cl::opt<bool> UseLIRCodeSizeHeurs(
75 "use-lir-code-size-heurs",
76 cl::desc("Use loop idiom recognition code size heuristics when compiling"
78 cl::init(true), cl::Hidden);
82 class LoopIdiomRecognize {
88 TargetLibraryInfo *TLI;
89 const TargetTransformInfo *TTI;
91 bool ApplyCodeSizeHeuristics;
94 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
95 LoopInfo *LI, ScalarEvolution *SE,
96 TargetLibraryInfo *TLI,
97 const TargetTransformInfo *TTI,
99 : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
102 bool runOnLoop(Loop *L);
105 typedef SmallVector<StoreInst *, 8> StoreList;
106 typedef MapVector<Value *, StoreList> StoreListMap;
107 StoreListMap StoreRefsForMemset;
108 StoreListMap StoreRefsForMemsetPattern;
109 StoreList StoreRefsForMemcpy;
111 bool HasMemsetPattern;
113 /// Return code for isLegalStore()
114 enum LegalStoreKind {
119 UnorderedAtomicMemcpy,
120 DontUse // Dummy retval never to be used. Allows catching errors in retval
124 /// \name Countable Loop Idiom Handling
127 bool runOnCountableLoop();
128 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
129 SmallVectorImpl<BasicBlock *> &ExitBlocks);
131 void collectStores(BasicBlock *BB);
132 LegalStoreKind isLegalStore(StoreInst *SI);
133 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
135 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
137 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
138 unsigned StoreAlignment, Value *StoredVal,
139 Instruction *TheStore,
140 SmallPtrSetImpl<Instruction *> &Stores,
141 const SCEVAddRecExpr *Ev, const SCEV *BECount,
142 bool NegStride, bool IsLoopMemset = false);
143 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
144 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
145 bool IsLoopMemset = false);
148 /// \name Noncountable Loop Idiom Handling
151 bool runOnNoncountableLoop();
153 bool recognizePopcount();
154 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
155 PHINode *CntPhi, Value *Var);
156 bool recognizeAndInsertCTLZ();
157 void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst,
158 PHINode *CntPhi, Value *Var, const DebugLoc DL,
159 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop);
164 class LoopIdiomRecognizeLegacyPass : public LoopPass {
167 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
168 initializeLoopIdiomRecognizeLegacyPassPass(
169 *PassRegistry::getPassRegistry());
172 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
176 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
177 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
178 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
179 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
180 TargetLibraryInfo *TLI =
181 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
182 const TargetTransformInfo *TTI =
183 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
184 *L->getHeader()->getParent());
185 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
187 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
188 return LIR.runOnLoop(L);
191 /// This transformation requires natural loop information & requires that
192 /// loop preheaders be inserted into the CFG.
194 void getAnalysisUsage(AnalysisUsage &AU) const override {
195 AU.addRequired<TargetLibraryInfoWrapperPass>();
196 AU.addRequired<TargetTransformInfoWrapperPass>();
197 getLoopAnalysisUsage(AU);
200 } // End anonymous namespace.
202 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
203 LoopStandardAnalysisResults &AR,
205 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
207 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
208 if (!LIR.runOnLoop(&L))
209 return PreservedAnalyses::all();
211 return getLoopPassPreservedAnalyses();
214 char LoopIdiomRecognizeLegacyPass::ID = 0;
215 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
216 "Recognize loop idioms", false, false)
217 INITIALIZE_PASS_DEPENDENCY(LoopPass)
218 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
219 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
220 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
221 "Recognize loop idioms", false, false)
223 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
225 static void deleteDeadInstruction(Instruction *I) {
226 I->replaceAllUsesWith(UndefValue::get(I->getType()));
227 I->eraseFromParent();
230 //===----------------------------------------------------------------------===//
232 // Implementation of LoopIdiomRecognize
234 //===----------------------------------------------------------------------===//
236 bool LoopIdiomRecognize::runOnLoop(Loop *L) {
238 // If the loop could not be converted to canonical form, it must have an
239 // indirectbr in it, just give up.
240 if (!L->getLoopPreheader())
243 // Disable loop idiom recognition if the function's name is a common idiom.
244 StringRef Name = L->getHeader()->getParent()->getName();
245 if (Name == "memset" || Name == "memcpy")
248 // Determine if code size heuristics need to be applied.
249 ApplyCodeSizeHeuristics =
250 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
252 HasMemset = TLI->has(LibFunc_memset);
253 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
254 HasMemcpy = TLI->has(LibFunc_memcpy);
256 if (HasMemset || HasMemsetPattern || HasMemcpy)
257 if (SE->hasLoopInvariantBackedgeTakenCount(L))
258 return runOnCountableLoop();
260 return runOnNoncountableLoop();
263 bool LoopIdiomRecognize::runOnCountableLoop() {
264 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
265 assert(!isa<SCEVCouldNotCompute>(BECount) &&
266 "runOnCountableLoop() called on a loop without a predictable"
267 "backedge-taken count");
269 // If this loop executes exactly one time, then it should be peeled, not
270 // optimized by this pass.
271 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
272 if (BECst->getAPInt() == 0)
275 SmallVector<BasicBlock *, 8> ExitBlocks;
276 CurLoop->getUniqueExitBlocks(ExitBlocks);
278 DEBUG(dbgs() << "loop-idiom Scanning: F["
279 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
280 << CurLoop->getHeader()->getName() << "\n");
282 bool MadeChange = false;
284 // The following transforms hoist stores/memsets into the loop pre-header.
285 // Give up if the loop has instructions may throw.
286 LoopSafetyInfo SafetyInfo;
287 computeLoopSafetyInfo(&SafetyInfo, CurLoop);
288 if (SafetyInfo.MayThrow)
291 // Scan all the blocks in the loop that are not in subloops.
292 for (auto *BB : CurLoop->getBlocks()) {
293 // Ignore blocks in subloops.
294 if (LI->getLoopFor(BB) != CurLoop)
297 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
302 static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
303 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
304 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
305 "Don't overflow unsigned.");
306 return (unsigned)SizeInBits >> 3;
309 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
310 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
311 return ConstStride->getAPInt();
314 /// getMemSetPatternValue - If a strided store of the specified value is safe to
315 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
316 /// be passed in. Otherwise, return null.
318 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
319 /// just replicate their input array and then pass on to memset_pattern16.
320 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
321 // If the value isn't a constant, we can't promote it to being in a constant
322 // array. We could theoretically do a store to an alloca or something, but
323 // that doesn't seem worthwhile.
324 Constant *C = dyn_cast<Constant>(V);
328 // Only handle simple values that are a power of two bytes in size.
329 uint64_t Size = DL->getTypeSizeInBits(V->getType());
330 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
333 // Don't care enough about darwin/ppc to implement this.
334 if (DL->isBigEndian())
337 // Convert to size in bytes.
340 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
341 // if the top and bottom are the same (e.g. for vectors and large integers).
345 // If the constant is exactly 16 bytes, just use it.
349 // Otherwise, we'll use an array of the constants.
350 unsigned ArraySize = 16 / Size;
351 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
352 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
355 LoopIdiomRecognize::LegalStoreKind
356 LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
358 // Don't touch volatile stores.
359 if (SI->isVolatile())
360 return LegalStoreKind::None;
361 // We only want simple or unordered-atomic stores.
362 if (!SI->isUnordered())
363 return LegalStoreKind::None;
365 // Don't convert stores of non-integral pointer types to memsets (which stores
367 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
368 return LegalStoreKind::None;
370 // Avoid merging nontemporal stores.
371 if (SI->getMetadata(LLVMContext::MD_nontemporal))
372 return LegalStoreKind::None;
374 Value *StoredVal = SI->getValueOperand();
375 Value *StorePtr = SI->getPointerOperand();
377 // Reject stores that are so large that they overflow an unsigned.
378 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
379 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
380 return LegalStoreKind::None;
382 // See if the pointer expression is an AddRec like {base,+,1} on the current
383 // loop, which indicates a strided store. If we have something else, it's a
384 // random store we can't handle.
385 const SCEVAddRecExpr *StoreEv =
386 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
387 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
388 return LegalStoreKind::None;
390 // Check to see if we have a constant stride.
391 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
392 return LegalStoreKind::None;
394 // See if the store can be turned into a memset.
396 // If the stored value is a byte-wise value (like i32 -1), then it may be
397 // turned into a memset of i8 -1, assuming that all the consecutive bytes
398 // are stored. A store of i32 0x01020304 can never be turned into a memset,
399 // but it can be turned into memset_pattern if the target supports it.
400 Value *SplatValue = isBytewiseValue(StoredVal);
401 Constant *PatternValue = nullptr;
403 // Note: memset and memset_pattern on unordered-atomic is yet not supported
404 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
406 // If we're allowed to form a memset, and the stored value would be
407 // acceptable for memset, use it.
408 if (!UnorderedAtomic && HasMemset && SplatValue &&
409 // Verify that the stored value is loop invariant. If not, we can't
410 // promote the memset.
411 CurLoop->isLoopInvariant(SplatValue)) {
412 // It looks like we can use SplatValue.
413 return LegalStoreKind::Memset;
414 } else if (!UnorderedAtomic && HasMemsetPattern &&
415 // Don't create memset_pattern16s with address spaces.
416 StorePtr->getType()->getPointerAddressSpace() == 0 &&
417 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
418 // It looks like we can use PatternValue!
419 return LegalStoreKind::MemsetPattern;
422 // Otherwise, see if the store can be turned into a memcpy.
424 // Check to see if the stride matches the size of the store. If so, then we
425 // know that every byte is touched in the loop.
426 APInt Stride = getStoreStride(StoreEv);
427 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
428 if (StoreSize != Stride && StoreSize != -Stride)
429 return LegalStoreKind::None;
431 // The store must be feeding a non-volatile load.
432 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
434 // Only allow non-volatile loads
435 if (!LI || LI->isVolatile())
436 return LegalStoreKind::None;
437 // Only allow simple or unordered-atomic loads
438 if (!LI->isUnordered())
439 return LegalStoreKind::None;
441 // See if the pointer expression is an AddRec like {base,+,1} on the current
442 // loop, which indicates a strided load. If we have something else, it's a
443 // random load we can't handle.
444 const SCEVAddRecExpr *LoadEv =
445 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
446 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
447 return LegalStoreKind::None;
449 // The store and load must share the same stride.
450 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
451 return LegalStoreKind::None;
453 // Success. This store can be converted into a memcpy.
454 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
455 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
456 : LegalStoreKind::Memcpy;
458 // This store can't be transformed into a memset/memcpy.
459 return LegalStoreKind::None;
462 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
463 StoreRefsForMemset.clear();
464 StoreRefsForMemsetPattern.clear();
465 StoreRefsForMemcpy.clear();
466 for (Instruction &I : *BB) {
467 StoreInst *SI = dyn_cast<StoreInst>(&I);
471 // Make sure this is a strided store with a constant stride.
472 switch (isLegalStore(SI)) {
473 case LegalStoreKind::None:
476 case LegalStoreKind::Memset: {
477 // Find the base pointer.
478 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
479 StoreRefsForMemset[Ptr].push_back(SI);
481 case LegalStoreKind::MemsetPattern: {
482 // Find the base pointer.
483 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
484 StoreRefsForMemsetPattern[Ptr].push_back(SI);
486 case LegalStoreKind::Memcpy:
487 case LegalStoreKind::UnorderedAtomicMemcpy:
488 StoreRefsForMemcpy.push_back(SI);
491 assert(false && "unhandled return value");
497 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
498 /// with the specified backedge count. This block is known to be in the current
499 /// loop and not in any subloops.
500 bool LoopIdiomRecognize::runOnLoopBlock(
501 BasicBlock *BB, const SCEV *BECount,
502 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
503 // We can only promote stores in this block if they are unconditionally
504 // executed in the loop. For a block to be unconditionally executed, it has
505 // to dominate all the exit blocks of the loop. Verify this now.
506 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
507 if (!DT->dominates(BB, ExitBlocks[i]))
510 bool MadeChange = false;
511 // Look for store instructions, which may be optimized to memset/memcpy.
514 // Look for a single store or sets of stores with a common base, which can be
515 // optimized into a memset (memset_pattern). The latter most commonly happens
516 // with structs and handunrolled loops.
517 for (auto &SL : StoreRefsForMemset)
518 MadeChange |= processLoopStores(SL.second, BECount, true);
520 for (auto &SL : StoreRefsForMemsetPattern)
521 MadeChange |= processLoopStores(SL.second, BECount, false);
523 // Optimize the store into a memcpy, if it feeds an similarly strided load.
524 for (auto &SI : StoreRefsForMemcpy)
525 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
527 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
528 Instruction *Inst = &*I++;
529 // Look for memset instructions, which may be optimized to a larger memset.
530 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
531 WeakTrackingVH InstPtr(&*I);
532 if (!processLoopMemSet(MSI, BECount))
536 // If processing the memset invalidated our iterator, start over from the
547 /// processLoopStores - See if this store(s) can be promoted to a memset.
548 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
551 // Try to find consecutive stores that can be transformed into memsets.
552 SetVector<StoreInst *> Heads, Tails;
553 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
555 // Do a quadratic search on all of the given stores and find
556 // all of the pairs of stores that follow each other.
557 SmallVector<unsigned, 16> IndexQueue;
558 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
559 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
561 Value *FirstStoredVal = SL[i]->getValueOperand();
562 Value *FirstStorePtr = SL[i]->getPointerOperand();
563 const SCEVAddRecExpr *FirstStoreEv =
564 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
565 APInt FirstStride = getStoreStride(FirstStoreEv);
566 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
568 // See if we can optimize just this store in isolation.
569 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
574 Value *FirstSplatValue = nullptr;
575 Constant *FirstPatternValue = nullptr;
578 FirstSplatValue = isBytewiseValue(FirstStoredVal);
580 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
582 assert((FirstSplatValue || FirstPatternValue) &&
583 "Expected either splat value or pattern value.");
586 // If a store has multiple consecutive store candidates, search Stores
587 // array according to the sequence: from i+1 to e, then from i-1 to 0.
588 // This is because usually pairing with immediate succeeding or preceding
589 // candidate create the best chance to find memset opportunity.
591 for (j = i + 1; j < e; ++j)
592 IndexQueue.push_back(j);
593 for (j = i; j > 0; --j)
594 IndexQueue.push_back(j - 1);
596 for (auto &k : IndexQueue) {
597 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
598 Value *SecondStorePtr = SL[k]->getPointerOperand();
599 const SCEVAddRecExpr *SecondStoreEv =
600 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
601 APInt SecondStride = getStoreStride(SecondStoreEv);
603 if (FirstStride != SecondStride)
606 Value *SecondStoredVal = SL[k]->getValueOperand();
607 Value *SecondSplatValue = nullptr;
608 Constant *SecondPatternValue = nullptr;
611 SecondSplatValue = isBytewiseValue(SecondStoredVal);
613 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
615 assert((SecondSplatValue || SecondPatternValue) &&
616 "Expected either splat value or pattern value.");
618 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
620 if (FirstSplatValue != SecondSplatValue)
623 if (FirstPatternValue != SecondPatternValue)
628 ConsecutiveChain[SL[i]] = SL[k];
634 // We may run into multiple chains that merge into a single chain. We mark the
635 // stores that we transformed so that we don't visit the same store twice.
636 SmallPtrSet<Value *, 16> TransformedStores;
637 bool Changed = false;
639 // For stores that start but don't end a link in the chain:
640 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
642 if (Tails.count(*it))
645 // We found a store instr that starts a chain. Now follow the chain and try
647 SmallPtrSet<Instruction *, 8> AdjacentStores;
650 StoreInst *HeadStore = I;
651 unsigned StoreSize = 0;
653 // Collect the chain into a list.
654 while (Tails.count(I) || Heads.count(I)) {
655 if (TransformedStores.count(I))
657 AdjacentStores.insert(I);
659 StoreSize += getStoreSizeInBytes(I, DL);
660 // Move to the next value in the chain.
661 I = ConsecutiveChain[I];
664 Value *StoredVal = HeadStore->getValueOperand();
665 Value *StorePtr = HeadStore->getPointerOperand();
666 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
667 APInt Stride = getStoreStride(StoreEv);
669 // Check to see if the stride matches the size of the stores. If so, then
670 // we know that every byte is touched in the loop.
671 if (StoreSize != Stride && StoreSize != -Stride)
674 bool NegStride = StoreSize == -Stride;
676 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
677 StoredVal, HeadStore, AdjacentStores, StoreEv,
678 BECount, NegStride)) {
679 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
687 /// processLoopMemSet - See if this memset can be promoted to a large memset.
688 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
689 const SCEV *BECount) {
690 // We can only handle non-volatile memsets with a constant size.
691 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
694 // If we're not allowed to hack on memset, we fail.
698 Value *Pointer = MSI->getDest();
700 // See if the pointer expression is an AddRec like {base,+,1} on the current
701 // loop, which indicates a strided store. If we have something else, it's a
702 // random store we can't handle.
703 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
704 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
707 // Reject memsets that are so large that they overflow an unsigned.
708 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
709 if ((SizeInBytes >> 32) != 0)
712 // Check to see if the stride matches the size of the memset. If so, then we
713 // know that every byte is touched in the loop.
714 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
718 APInt Stride = ConstStride->getAPInt();
719 if (SizeInBytes != Stride && SizeInBytes != -Stride)
722 // Verify that the memset value is loop invariant. If not, we can't promote
724 Value *SplatValue = MSI->getValue();
725 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
728 SmallPtrSet<Instruction *, 1> MSIs;
730 bool NegStride = SizeInBytes == -Stride;
731 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
732 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
733 BECount, NegStride, /*IsLoopMemset=*/true);
736 /// mayLoopAccessLocation - Return true if the specified loop might access the
737 /// specified pointer location, which is a loop-strided access. The 'Access'
738 /// argument specifies what the verboten forms of access are (read or write).
740 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
741 const SCEV *BECount, unsigned StoreSize,
743 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
744 // Get the location that may be stored across the loop. Since the access is
745 // strided positively through memory, we say that the modified location starts
746 // at the pointer and has infinite size.
747 uint64_t AccessSize = MemoryLocation::UnknownSize;
749 // If the loop iterates a fixed number of times, we can refine the access size
750 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
751 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
752 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
754 // TODO: For this to be really effective, we have to dive into the pointer
755 // operand in the store. Store to &A[i] of 100 will always return may alias
756 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
757 // which will then no-alias a store to &A[100].
758 MemoryLocation StoreLoc(Ptr, AccessSize);
760 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
762 for (Instruction &I : **BI)
763 if (IgnoredStores.count(&I) == 0 &&
764 (AA.getModRefInfo(&I, StoreLoc) & Access))
770 // If we have a negative stride, Start refers to the end of the memory location
771 // we're trying to memset. Therefore, we need to recompute the base pointer,
772 // which is just Start - BECount*Size.
773 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
774 Type *IntPtr, unsigned StoreSize,
775 ScalarEvolution *SE) {
776 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
778 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
780 return SE->getMinusSCEV(Start, Index);
783 /// processLoopStridedStore - We see a strided store of some value. If we can
784 /// transform this into a memset or memset_pattern in the loop preheader, do so.
785 bool LoopIdiomRecognize::processLoopStridedStore(
786 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
787 Value *StoredVal, Instruction *TheStore,
788 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
789 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
790 Value *SplatValue = isBytewiseValue(StoredVal);
791 Constant *PatternValue = nullptr;
794 PatternValue = getMemSetPatternValue(StoredVal, DL);
796 assert((SplatValue || PatternValue) &&
797 "Expected either splat value or pattern value.");
799 // The trip count of the loop and the base pointer of the addrec SCEV is
800 // guaranteed to be loop invariant, which means that it should dominate the
801 // header. This allows us to insert code for it in the preheader.
802 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
803 BasicBlock *Preheader = CurLoop->getLoopPreheader();
804 IRBuilder<> Builder(Preheader->getTerminator());
805 SCEVExpander Expander(*SE, *DL, "loop-idiom");
807 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
808 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
810 const SCEV *Start = Ev->getStart();
811 // Handle negative strided loops.
813 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
815 // TODO: ideally we should still be able to generate memset if SCEV expander
816 // is taught to generate the dependencies at the latest point.
817 if (!isSafeToExpand(Start, *SE))
820 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
821 // this into a memset in the loop preheader now if we want. However, this
822 // would be unsafe to do if there is anything else in the loop that may read
823 // or write to the aliased location. Check for any overlap by generating the
824 // base pointer and checking the region.
826 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
827 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
830 // If we generated new code for the base pointer, clean up.
831 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
835 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
838 // Okay, everything looks good, insert the memset.
840 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
841 // pointer size if it isn't already.
842 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
844 const SCEV *NumBytesS =
845 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
846 if (StoreSize != 1) {
847 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
851 // TODO: ideally we should still be able to generate memset if SCEV expander
852 // is taught to generate the dependencies at the latest point.
853 if (!isSafeToExpand(NumBytesS, *SE))
857 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
862 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
864 // Everything is emitted in default address space
865 Type *Int8PtrTy = DestInt8PtrTy;
867 Module *M = TheStore->getModule();
869 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
870 Int8PtrTy, Int8PtrTy, IntPtr);
871 inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
873 // Otherwise we should form a memset_pattern16. PatternValue is known to be
874 // an constant array of 16-bytes. Plop the value into a mergable global.
875 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
876 GlobalValue::PrivateLinkage,
877 PatternValue, ".memset_pattern");
878 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
879 GV->setAlignment(16);
880 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
881 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
884 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
885 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
886 NewCall->setDebugLoc(TheStore->getDebugLoc());
888 // Okay, the memset has been formed. Zap the original store and anything that
890 for (auto *I : Stores)
891 deleteDeadInstruction(I);
896 /// If the stored value is a strided load in the same loop with the same stride
897 /// this may be transformable into a memcpy. This kicks in for stuff like
898 /// for (i) A[i] = B[i];
899 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
900 const SCEV *BECount) {
901 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
903 Value *StorePtr = SI->getPointerOperand();
904 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
905 APInt Stride = getStoreStride(StoreEv);
906 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
907 bool NegStride = StoreSize == -Stride;
909 // The store must be feeding a non-volatile load.
910 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
911 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
913 // See if the pointer expression is an AddRec like {base,+,1} on the current
914 // loop, which indicates a strided load. If we have something else, it's a
915 // random load we can't handle.
916 const SCEVAddRecExpr *LoadEv =
917 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
919 // The trip count of the loop and the base pointer of the addrec SCEV is
920 // guaranteed to be loop invariant, which means that it should dominate the
921 // header. This allows us to insert code for it in the preheader.
922 BasicBlock *Preheader = CurLoop->getLoopPreheader();
923 IRBuilder<> Builder(Preheader->getTerminator());
924 SCEVExpander Expander(*SE, *DL, "loop-idiom");
926 const SCEV *StrStart = StoreEv->getStart();
927 unsigned StrAS = SI->getPointerAddressSpace();
928 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
930 // Handle negative strided loops.
932 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
934 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
935 // this into a memcpy in the loop preheader now if we want. However, this
936 // would be unsafe to do if there is anything else in the loop that may read
937 // or write the memory region we're storing to. This includes the load that
938 // feeds the stores. Check for an alias by generating the base address and
939 // checking everything.
940 Value *StoreBasePtr = Expander.expandCodeFor(
941 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
943 SmallPtrSet<Instruction *, 1> Stores;
945 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
946 StoreSize, *AA, Stores)) {
948 // If we generated new code for the base pointer, clean up.
949 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
953 const SCEV *LdStart = LoadEv->getStart();
954 unsigned LdAS = LI->getPointerAddressSpace();
956 // Handle negative strided loops.
958 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
960 // For a memcpy, we have to make sure that the input array is not being
961 // mutated by the loop.
962 Value *LoadBasePtr = Expander.expandCodeFor(
963 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
965 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
968 // If we generated new code for the base pointer, clean up.
969 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
970 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
974 if (avoidLIRForMultiBlockLoop())
977 // Okay, everything is safe, we can transform this!
979 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
980 // pointer size if it isn't already.
981 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
983 const SCEV *NumBytesS =
984 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
986 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
987 CallInst *NewCall = nullptr;
988 // Check whether to generate an unordered atomic memcpy:
989 // If the load or store are atomic, then they must neccessarily be unordered
990 // by previous checks.
991 if (!SI->isAtomic() && !LI->isAtomic()) {
993 NumBytesS = SE->getMulExpr(
994 NumBytesS, SE->getConstant(IntPtrTy, StoreSize), SCEV::FlagNUW);
997 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
999 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
1001 // We cannot allow unaligned ops for unordered load/store, so reject
1002 // anything where the alignment isn't at least the element size.
1003 if (Align < StoreSize)
1006 // If the element.atomic memcpy is not lowered into explicit
1007 // loads/stores later, then it will be lowered into an element-size
1008 // specific lib call. If the lib call doesn't exist for our store size, then
1009 // we shouldn't generate the memcpy.
1010 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1013 Value *NumElements =
1014 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1016 NewCall = Builder.CreateElementAtomicMemCpy(StoreBasePtr, LoadBasePtr,
1017 NumElements, StoreSize);
1018 // Propagate alignment info onto the pointer args. Note that unordered
1019 // atomic loads/stores are *required* by the spec to have an alignment
1020 // but non-atomic loads/stores may not.
1021 NewCall->addParamAttr(0, Attribute::getWithAlignment(NewCall->getContext(),
1022 SI->getAlignment()));
1023 NewCall->addParamAttr(1, Attribute::getWithAlignment(NewCall->getContext(),
1024 LI->getAlignment()));
1026 NewCall->setDebugLoc(SI->getDebugLoc());
1028 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1029 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1030 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1032 // Okay, the memcpy has been formed. Zap the original store and anything that
1034 deleteDeadInstruction(SI);
1039 // When compiling for codesize we avoid idiom recognition for a multi-block loop
1040 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1042 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1043 bool IsLoopMemset) {
1044 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1045 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1046 DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1047 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1048 << " avoided: multi-block top-level loop\n");
1056 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1057 return recognizePopcount() || recognizeAndInsertCTLZ();
1060 /// Check if the given conditional branch is based on the comparison between
1061 /// a variable and zero, and if the variable is non-zero, the control yields to
1062 /// the loop entry. If the branch matches the behavior, the variable involved
1063 /// in the comparison is returned. This function will be called to see if the
1064 /// precondition and postcondition of the loop are in desirable form.
1065 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1066 if (!BI || !BI->isConditional())
1069 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1073 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1074 if (!CmpZero || !CmpZero->isZero())
1077 ICmpInst::Predicate Pred = Cond->getPredicate();
1078 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1079 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1080 return Cond->getOperand(0);
1085 // Check if the recurrence variable `VarX` is in the right form to create
1086 // the idiom. Returns the value coerced to a PHINode if so.
1087 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1088 BasicBlock *LoopEntry) {
1089 auto *PhiX = dyn_cast<PHINode>(VarX);
1090 if (PhiX && PhiX->getParent() == LoopEntry &&
1091 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1096 /// Return true iff the idiom is detected in the loop.
1099 /// 1) \p CntInst is set to the instruction counting the population bit.
1100 /// 2) \p CntPhi is set to the corresponding phi node.
1101 /// 3) \p Var is set to the value whose population bits are being counted.
1103 /// The core idiom we are trying to detect is:
1106 /// goto loop-exit // the precondition of the loop
1107 /// cnt0 = init-val;
1109 /// x1 = phi (x0, x2);
1110 /// cnt1 = phi(cnt0, cnt2);
1112 /// cnt2 = cnt1 + 1;
1114 /// x2 = x1 & (x1 - 1);
1116 /// } while(x != 0);
1120 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1121 Instruction *&CntInst, PHINode *&CntPhi,
1123 // step 1: Check to see if the look-back branch match this pattern:
1124 // "if (a!=0) goto loop-entry".
1125 BasicBlock *LoopEntry;
1126 Instruction *DefX2, *CountInst;
1127 Value *VarX1, *VarX0;
1128 PHINode *PhiX, *CountPhi;
1130 DefX2 = CountInst = nullptr;
1131 VarX1 = VarX0 = nullptr;
1132 PhiX = CountPhi = nullptr;
1133 LoopEntry = *(CurLoop->block_begin());
1135 // step 1: Check if the loop-back branch is in desirable form.
1137 if (Value *T = matchCondition(
1138 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1139 DefX2 = dyn_cast<Instruction>(T);
1144 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1146 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1149 BinaryOperator *SubOneOp;
1151 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1152 VarX1 = DefX2->getOperand(1);
1154 VarX1 = DefX2->getOperand(0);
1155 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1160 Instruction *SubInst = cast<Instruction>(SubOneOp);
1161 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1163 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1164 (SubInst->getOpcode() == Instruction::Add &&
1165 Dec->isAllOnesValue()))) {
1170 // step 3: Check the recurrence of variable X
1171 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1175 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1177 CountInst = nullptr;
1178 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1179 IterE = LoopEntry->end();
1180 Iter != IterE; Iter++) {
1181 Instruction *Inst = &*Iter;
1182 if (Inst->getOpcode() != Instruction::Add)
1185 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1186 if (!Inc || !Inc->isOne())
1189 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1193 // Check if the result of the instruction is live of the loop.
1194 bool LiveOutLoop = false;
1195 for (User *U : Inst->users()) {
1196 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1213 // step 5: check if the precondition is in this form:
1214 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1216 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1217 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1218 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1221 CntInst = CountInst;
1229 /// Return true if the idiom is detected in the loop.
1232 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1233 /// or nullptr if there is no such.
1234 /// 2) \p CntPhi is set to the corresponding phi node
1235 /// or nullptr if there is no such.
1236 /// 3) \p Var is set to the value whose CTLZ could be used.
1237 /// 4) \p DefX is set to the instruction calculating Loop exit condition.
1239 /// The core idiom we are trying to detect is:
1242 /// goto loop-exit // the precondition of the loop
1243 /// cnt0 = init-val;
1245 /// x = phi (x0, x.next); //PhiX
1246 /// cnt = phi(cnt0, cnt.next);
1248 /// cnt.next = cnt + 1;
1250 /// x.next = x >> 1; // DefX
1252 /// } while(x.next != 0);
1256 static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX,
1257 Instruction *&CntInst, PHINode *&CntPhi,
1258 Instruction *&DefX) {
1259 BasicBlock *LoopEntry;
1260 Value *VarX = nullptr;
1266 LoopEntry = *(CurLoop->block_begin());
1268 // step 1: Check if the loop-back branch is in desirable form.
1269 if (Value *T = matchCondition(
1270 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1271 DefX = dyn_cast<Instruction>(T);
1275 // step 2: detect instructions corresponding to "x.next = x >> 1"
1276 if (!DefX || DefX->getOpcode() != Instruction::AShr)
1278 if (ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)))
1279 if (!Shft || !Shft->isOne())
1281 VarX = DefX->getOperand(0);
1283 // step 3: Check the recurrence of variable X
1284 PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1288 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1289 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1290 // then all uses of "cnt.next" could be optimized to the trip count
1291 // plus "cnt0". Currently it is not optimized.
1292 // This step could be used to detect POPCNT instruction:
1293 // cnt.next = cnt + (x.next & 1)
1294 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1295 IterE = LoopEntry->end();
1296 Iter != IterE; Iter++) {
1297 Instruction *Inst = &*Iter;
1298 if (Inst->getOpcode() != Instruction::Add)
1301 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1302 if (!Inc || !Inc->isOne())
1305 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1319 /// Recognize CTLZ idiom in a non-countable loop and convert the loop
1320 /// to countable (with CTLZ trip count).
1321 /// If CTLZ inserted as a new trip count returns true; otherwise, returns false.
1322 bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1323 // Give up if the loop has multiple blocks or multiple backedges.
1324 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1327 Instruction *CntInst, *DefX;
1328 PHINode *CntPhi, *PhiX;
1329 if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX))
1332 bool IsCntPhiUsedOutsideLoop = false;
1333 for (User *U : CntPhi->users())
1334 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1335 IsCntPhiUsedOutsideLoop = true;
1338 bool IsCntInstUsedOutsideLoop = false;
1339 for (User *U : CntInst->users())
1340 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1341 IsCntInstUsedOutsideLoop = true;
1344 // If both CntInst and CntPhi are used outside the loop the profitability
1346 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1349 // For some CPUs result of CTLZ(X) intrinsic is undefined
1350 // when X is 0. If we can not guarantee X != 0, we need to check this
1352 bool ZeroCheck = false;
1353 // It is safe to assume Preheader exist as it was checked in
1354 // parent function RunOnLoop.
1355 BasicBlock *PH = CurLoop->getLoopPreheader();
1356 Value *InitX = PhiX->getIncomingValueForBlock(PH);
1357 // If we check X != 0 before entering the loop we don't need a zero
1358 // check in CTLZ intrinsic, but only if Cnt Phi is not used outside of the
1359 // loop (if it is used we count CTLZ(X >> 1)).
1360 if (!IsCntPhiUsedOutsideLoop)
1361 if (BasicBlock *PreCondBB = PH->getSinglePredecessor())
1362 if (BranchInst *PreCondBr =
1363 dyn_cast<BranchInst>(PreCondBB->getTerminator())) {
1364 if (matchCondition(PreCondBr, PH) == InitX)
1368 // Check if CTLZ intrinsic is profitable. Assume it is always profitable
1369 // if we delete the loop (the loop has only 6 instructions):
1370 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1371 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1372 // %shr = ashr %n.addr.0, 1
1373 // %tobool = icmp eq %shr, 0
1374 // %inc = add nsw %i.0, 1
1377 IRBuilder<> Builder(PH->getTerminator());
1378 SmallVector<const Value *, 2> Ops =
1379 {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()};
1380 ArrayRef<const Value *> Args(Ops);
1381 if (CurLoop->getHeader()->size() != 6 &&
1382 TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) >
1383 TargetTransformInfo::TCC_Basic)
1386 const DebugLoc DL = DefX->getDebugLoc();
1387 transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck,
1388 IsCntPhiUsedOutsideLoop);
1392 /// Recognizes a population count idiom in a non-countable loop.
1394 /// If detected, transforms the relevant code to issue the popcount intrinsic
1395 /// function call, and returns true; otherwise, returns false.
1396 bool LoopIdiomRecognize::recognizePopcount() {
1397 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1400 // Counting population are usually conducted by few arithmetic instructions.
1401 // Such instructions can be easily "absorbed" by vacant slots in a
1402 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1403 // in a compact loop.
1405 // Give up if the loop has multiple blocks or multiple backedges.
1406 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1409 BasicBlock *LoopBody = *(CurLoop->block_begin());
1410 if (LoopBody->size() >= 20) {
1411 // The loop is too big, bail out.
1415 // It should have a preheader containing nothing but an unconditional branch.
1416 BasicBlock *PH = CurLoop->getLoopPreheader();
1417 if (!PH || &PH->front() != PH->getTerminator())
1419 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1420 if (!EntryBI || EntryBI->isConditional())
1423 // It should have a precondition block where the generated popcount instrinsic
1424 // function can be inserted.
1425 auto *PreCondBB = PH->getSinglePredecessor();
1428 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1429 if (!PreCondBI || PreCondBI->isUnconditional())
1432 Instruction *CntInst;
1435 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1438 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1442 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1443 const DebugLoc &DL) {
1444 Value *Ops[] = {Val};
1445 Type *Tys[] = {Val->getType()};
1447 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1448 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1449 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1450 CI->setDebugLoc(DL);
1455 static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1456 const DebugLoc &DL, bool ZeroCheck) {
1457 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1458 Type *Tys[] = {Val->getType()};
1460 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1461 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys);
1462 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1463 CI->setDebugLoc(DL);
1468 /// Transform the following loop:
1470 /// CntPhi = PHI [Cnt0, CntInst]
1471 /// PhiX = PHI [InitX, DefX]
1472 /// CntInst = CntPhi + 1
1473 /// DefX = PhiX >> 1
1475 /// Br: loop if (DefX != 0)
1476 /// Use(CntPhi) or Use(CntInst)
1479 /// If CntPhi used outside the loop:
1480 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1481 /// Count = CountPrev + 1
1483 /// Count = BitWidth(InitX) - CTLZ(InitX)
1485 /// CntPhi = PHI [Cnt0, CntInst]
1486 /// PhiX = PHI [InitX, DefX]
1487 /// PhiCount = PHI [Count, Dec]
1488 /// CntInst = CntPhi + 1
1489 /// DefX = PhiX >> 1
1490 /// Dec = PhiCount - 1
1492 /// Br: loop if (Dec != 0)
1493 /// Use(CountPrev + Cnt0) // Use(CntPhi)
1495 /// Use(Count + Cnt0) // Use(CntInst)
1497 /// If LOOP_BODY is empty the loop will be deleted.
1498 /// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1499 void LoopIdiomRecognize::transformLoopToCountable(
1500 BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX,
1501 const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1502 BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1504 // Step 1: Insert the CTLZ instruction at the end of the preheader block
1505 // Count = BitWidth - CTLZ(InitX);
1506 // If there are uses of CntPhi create:
1507 // CountPrev = BitWidth - CTLZ(InitX >> 1);
1508 IRBuilder<> Builder(PreheaderBr);
1509 Builder.SetCurrentDebugLocation(DL);
1510 Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1512 if (IsCntPhiUsedOutsideLoop)
1513 InitXNext = Builder.CreateAShr(InitX,
1514 ConstantInt::get(InitX->getType(), 1));
1517 CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck);
1518 Count = Builder.CreateSub(
1519 ConstantInt::get(CTLZ->getType(),
1520 CTLZ->getType()->getIntegerBitWidth()),
1522 if (IsCntPhiUsedOutsideLoop) {
1524 Count = Builder.CreateAdd(
1526 ConstantInt::get(CountPrev->getType(), 1));
1528 if (IsCntPhiUsedOutsideLoop)
1529 NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1530 cast<IntegerType>(CntInst->getType()));
1532 NewCount = Builder.CreateZExtOrTrunc(Count,
1533 cast<IntegerType>(CntInst->getType()));
1535 // If the CTLZ counter's initial value is not zero, insert Add Inst.
1536 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1537 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1538 if (!InitConst || !InitConst->isZero())
1539 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1541 // Step 2: Insert new IV and loop condition:
1544 // PhiCount = PHI [Count, Dec]
1546 // Dec = PhiCount - 1
1548 // Br: loop if (Dec != 0)
1549 BasicBlock *Body = *(CurLoop->block_begin());
1550 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1551 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1552 Type *Ty = Count->getType();
1554 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1556 Builder.SetInsertPoint(LbCond);
1557 Instruction *TcDec = cast<Instruction>(
1558 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1559 "tcdec", false, true));
1561 TcPhi->addIncoming(Count, Preheader);
1562 TcPhi->addIncoming(TcDec, Body);
1564 CmpInst::Predicate Pred =
1565 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1566 LbCond->setPredicate(Pred);
1567 LbCond->setOperand(0, TcDec);
1568 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1570 // Step 3: All the references to the original counter outside
1571 // the loop are replaced with the NewCount -- the value returned from
1572 // __builtin_ctlz(x).
1573 if (IsCntPhiUsedOutsideLoop)
1574 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1576 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1578 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1579 // loop. The loop would otherwise not be deleted even if it becomes empty.
1580 SE->forgetLoop(CurLoop);
1583 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1584 Instruction *CntInst,
1585 PHINode *CntPhi, Value *Var) {
1586 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1587 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1588 const DebugLoc DL = CntInst->getDebugLoc();
1590 // Assuming before transformation, the loop is following:
1591 // if (x) // the precondition
1592 // do { cnt++; x &= x - 1; } while(x);
1594 // Step 1: Insert the ctpop instruction at the end of the precondition block
1595 IRBuilder<> Builder(PreCondBr);
1596 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1598 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1599 NewCount = PopCntZext =
1600 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1602 if (NewCount != PopCnt)
1603 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1605 // TripCnt is exactly the number of iterations the loop has
1608 // If the population counter's initial value is not zero, insert Add Inst.
1609 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1610 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1611 if (!InitConst || !InitConst->isZero()) {
1612 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1613 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1617 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1618 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1619 // function would be partial dead code, and downstream passes will drag
1620 // it back from the precondition block to the preheader.
1622 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1624 Value *Opnd0 = PopCntZext;
1625 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1626 if (PreCond->getOperand(0) != Var)
1627 std::swap(Opnd0, Opnd1);
1629 ICmpInst *NewPreCond = cast<ICmpInst>(
1630 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1631 PreCondBr->setCondition(NewPreCond);
1633 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1636 // Step 3: Note that the population count is exactly the trip count of the
1637 // loop in question, which enable us to to convert the loop from noncountable
1638 // loop into a countable one. The benefit is twofold:
1640 // - If the loop only counts population, the entire loop becomes dead after
1641 // the transformation. It is a lot easier to prove a countable loop dead
1642 // than to prove a noncountable one. (In some C dialects, an infinite loop
1643 // isn't dead even if it computes nothing useful. In general, DCE needs
1644 // to prove a noncountable loop finite before safely delete it.)
1646 // - If the loop also performs something else, it remains alive.
1647 // Since it is transformed to countable form, it can be aggressively
1648 // optimized by some optimizations which are in general not applicable
1649 // to a noncountable loop.
1651 // After this step, this loop (conceptually) would look like following:
1652 // newcnt = __builtin_ctpop(x);
1655 // do { cnt++; x &= x-1; t--) } while (t > 0);
1656 BasicBlock *Body = *(CurLoop->block_begin());
1658 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1659 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1660 Type *Ty = TripCnt->getType();
1662 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1664 Builder.SetInsertPoint(LbCond);
1665 Instruction *TcDec = cast<Instruction>(
1666 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1667 "tcdec", false, true));
1669 TcPhi->addIncoming(TripCnt, PreHead);
1670 TcPhi->addIncoming(TcDec, Body);
1672 CmpInst::Predicate Pred =
1673 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1674 LbCond->setPredicate(Pred);
1675 LbCond->setOperand(0, TcDec);
1676 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1679 // Step 4: All the references to the original population counter outside
1680 // the loop are replaced with the NewCount -- the value returned from
1681 // __builtin_ctpop().
1682 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1684 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1685 // loop. The loop would otherwise not be deleted even if it becomes empty.
1686 SE->forgetLoop(CurLoop);