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 //===----------------------------------------------------------------------===//
18 // Future loop memory idioms to recognize:
19 // memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
22 // Future integer operation idioms to recognize:
25 // Beware that isel's default lowering for ctpop is highly inefficient for
26 // i64 and larger types when i64 is legal and the value has few bits set. It
27 // would be good to enhance isel to emit a loop for ctpop in this case.
29 // We should enhance the memset/memcpy recognition to handle multiple stores in
30 // the loop. This would handle things like:
31 // void foo(_Complex float *P)
32 // for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
34 // This could recognize common matrix multiplies and dot product idioms and
35 // replace them with calls to BLAS (if linked in??).
37 //===----------------------------------------------------------------------===//
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/BasicAliasAnalysis.h"
43 #include "llvm/Analysis/GlobalsModRef.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/TargetTransformInfo.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
61 #define DEBUG_TYPE "loop-idiom"
63 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
68 class LoopIdiomRecognize : public LoopPass {
74 TargetLibraryInfo *TLI;
75 const TargetTransformInfo *TTI;
80 explicit LoopIdiomRecognize() : LoopPass(ID) {
81 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
84 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
86 /// This transformation requires natural loop information & requires that
87 /// loop preheaders be inserted into the CFG.
89 void getAnalysisUsage(AnalysisUsage &AU) const override {
90 AU.addRequired<LoopInfoWrapperPass>();
91 AU.addPreserved<LoopInfoWrapperPass>();
92 AU.addRequiredID(LoopSimplifyID);
93 AU.addPreservedID(LoopSimplifyID);
94 AU.addRequiredID(LCSSAID);
95 AU.addPreservedID(LCSSAID);
96 AU.addRequired<AAResultsWrapperPass>();
97 AU.addPreserved<AAResultsWrapperPass>();
98 AU.addRequired<ScalarEvolutionWrapperPass>();
99 AU.addPreserved<ScalarEvolutionWrapperPass>();
100 AU.addPreserved<SCEVAAWrapperPass>();
101 AU.addRequired<DominatorTreeWrapperPass>();
102 AU.addPreserved<DominatorTreeWrapperPass>();
103 AU.addRequired<TargetLibraryInfoWrapperPass>();
104 AU.addRequired<TargetTransformInfoWrapperPass>();
105 AU.addPreserved<BasicAAWrapperPass>();
106 AU.addPreserved<GlobalsAAWrapperPass>();
110 typedef SmallVector<StoreInst *, 8> StoreList;
111 StoreList StoreRefsForMemset;
112 StoreList StoreRefsForMemcpy;
114 bool HasMemsetPattern;
117 /// \name Countable Loop Idiom Handling
120 bool runOnCountableLoop();
121 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
122 SmallVectorImpl<BasicBlock *> &ExitBlocks);
124 void collectStores(BasicBlock *BB);
125 bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemcpy);
126 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
127 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
129 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
130 unsigned StoreAlignment, Value *StoredVal,
131 Instruction *TheStore, const SCEVAddRecExpr *Ev,
132 const SCEV *BECount, bool NegStride);
133 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
136 /// \name Noncountable Loop Idiom Handling
139 bool runOnNoncountableLoop();
141 bool recognizePopcount();
142 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
143 PHINode *CntPhi, Value *Var);
148 } // End anonymous namespace.
150 char LoopIdiomRecognize::ID = 0;
151 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
153 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
154 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
155 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
156 INITIALIZE_PASS_DEPENDENCY(LCSSA)
157 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
158 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
159 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
160 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
161 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
162 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
163 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
164 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
167 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
169 /// deleteDeadInstruction - Delete this instruction. Before we do, go through
170 /// and zero out all the operands of this instruction. If any of them become
171 /// dead, delete them and the computation tree that feeds them.
173 static void deleteDeadInstruction(Instruction *I,
174 const TargetLibraryInfo *TLI) {
175 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
176 I->replaceAllUsesWith(UndefValue::get(I->getType()));
177 I->eraseFromParent();
178 for (Value *Op : Operands)
179 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
182 //===----------------------------------------------------------------------===//
184 // Implementation of LoopIdiomRecognize
186 //===----------------------------------------------------------------------===//
188 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
189 if (skipOptnoneFunction(L))
193 // If the loop could not be converted to canonical form, it must have an
194 // indirectbr in it, just give up.
195 if (!L->getLoopPreheader())
198 // Disable loop idiom recognition if the function's name is a common idiom.
199 StringRef Name = L->getHeader()->getParent()->getName();
200 if (Name == "memset" || Name == "memcpy")
203 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
204 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
205 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
206 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
207 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
208 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
209 *CurLoop->getHeader()->getParent());
210 DL = &CurLoop->getHeader()->getModule()->getDataLayout();
212 HasMemset = TLI->has(LibFunc::memset);
213 HasMemsetPattern = TLI->has(LibFunc::memset_pattern16);
214 HasMemcpy = TLI->has(LibFunc::memcpy);
216 if (HasMemset || HasMemsetPattern || HasMemcpy)
217 if (SE->hasLoopInvariantBackedgeTakenCount(L))
218 return runOnCountableLoop();
220 return runOnNoncountableLoop();
223 bool LoopIdiomRecognize::runOnCountableLoop() {
224 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
225 assert(!isa<SCEVCouldNotCompute>(BECount) &&
226 "runOnCountableLoop() called on a loop without a predictable"
227 "backedge-taken count");
229 // If this loop executes exactly one time, then it should be peeled, not
230 // optimized by this pass.
231 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
232 if (BECst->getAPInt() == 0)
235 SmallVector<BasicBlock *, 8> ExitBlocks;
236 CurLoop->getUniqueExitBlocks(ExitBlocks);
238 DEBUG(dbgs() << "loop-idiom Scanning: F["
239 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
240 << CurLoop->getHeader()->getName() << "\n");
242 bool MadeChange = false;
243 // Scan all the blocks in the loop that are not in subloops.
244 for (auto *BB : CurLoop->getBlocks()) {
245 // Ignore blocks in subloops.
246 if (LI->getLoopFor(BB) != CurLoop)
249 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
254 static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
255 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
256 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
257 "Don't overflow unsigned.");
258 return (unsigned)SizeInBits >> 3;
261 static unsigned getStoreStride(const SCEVAddRecExpr *StoreEv) {
262 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
263 return ConstStride->getAPInt().getZExtValue();
266 /// getMemSetPatternValue - If a strided store of the specified value is safe to
267 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
268 /// be passed in. Otherwise, return null.
270 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
271 /// just replicate their input array and then pass on to memset_pattern16.
272 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
273 // If the value isn't a constant, we can't promote it to being in a constant
274 // array. We could theoretically do a store to an alloca or something, but
275 // that doesn't seem worthwhile.
276 Constant *C = dyn_cast<Constant>(V);
280 // Only handle simple values that are a power of two bytes in size.
281 uint64_t Size = DL->getTypeSizeInBits(V->getType());
282 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
285 // Don't care enough about darwin/ppc to implement this.
286 if (DL->isBigEndian())
289 // Convert to size in bytes.
292 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
293 // if the top and bottom are the same (e.g. for vectors and large integers).
297 // If the constant is exactly 16 bytes, just use it.
301 // Otherwise, we'll use an array of the constants.
302 unsigned ArraySize = 16 / Size;
303 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
304 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
307 bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
309 // Don't touch volatile stores.
313 Value *StoredVal = SI->getValueOperand();
314 Value *StorePtr = SI->getPointerOperand();
316 // Reject stores that are so large that they overflow an unsigned.
317 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
318 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
321 // See if the pointer expression is an AddRec like {base,+,1} on the current
322 // loop, which indicates a strided store. If we have something else, it's a
323 // random store we can't handle.
324 const SCEVAddRecExpr *StoreEv =
325 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
326 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
329 // Check to see if we have a constant stride.
330 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
333 // See if the store can be turned into a memset.
335 // If the stored value is a byte-wise value (like i32 -1), then it may be
336 // turned into a memset of i8 -1, assuming that all the consecutive bytes
337 // are stored. A store of i32 0x01020304 can never be turned into a memset,
338 // but it can be turned into memset_pattern if the target supports it.
339 Value *SplatValue = isBytewiseValue(StoredVal);
340 Constant *PatternValue = nullptr;
342 // If we're allowed to form a memset, and the stored value would be
343 // acceptable for memset, use it.
344 if (HasMemset && SplatValue &&
345 // Verify that the stored value is loop invariant. If not, we can't
346 // promote the memset.
347 CurLoop->isLoopInvariant(SplatValue)) {
348 // It looks like we can use SplatValue.
351 } else if (HasMemsetPattern &&
352 // Don't create memset_pattern16s with address spaces.
353 StorePtr->getType()->getPointerAddressSpace() == 0 &&
354 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
355 // It looks like we can use PatternValue!
360 // Otherwise, see if the store can be turned into a memcpy.
362 // Check to see if the stride matches the size of the store. If so, then we
363 // know that every byte is touched in the loop.
364 unsigned Stride = getStoreStride(StoreEv);
365 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
366 if (StoreSize != Stride && StoreSize != -Stride)
369 // The store must be feeding a non-volatile load.
370 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
371 if (!LI || !LI->isSimple())
374 // See if the pointer expression is an AddRec like {base,+,1} on the current
375 // loop, which indicates a strided load. If we have something else, it's a
376 // random load we can't handle.
377 const SCEVAddRecExpr *LoadEv =
378 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
379 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
382 // The store and load must share the same stride.
383 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
386 // Success. This store can be converted into a memcpy.
390 // This store can't be transformed into a memset/memcpy.
394 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
395 StoreRefsForMemset.clear();
396 StoreRefsForMemcpy.clear();
397 for (Instruction &I : *BB) {
398 StoreInst *SI = dyn_cast<StoreInst>(&I);
402 bool ForMemset = false;
403 bool ForMemcpy = false;
404 // Make sure this is a strided store with a constant stride.
405 if (!isLegalStore(SI, ForMemset, ForMemcpy))
408 // Save the store locations.
410 StoreRefsForMemset.push_back(SI);
412 StoreRefsForMemcpy.push_back(SI);
416 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
417 /// with the specified backedge count. This block is known to be in the current
418 /// loop and not in any subloops.
419 bool LoopIdiomRecognize::runOnLoopBlock(
420 BasicBlock *BB, const SCEV *BECount,
421 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
422 // We can only promote stores in this block if they are unconditionally
423 // executed in the loop. For a block to be unconditionally executed, it has
424 // to dominate all the exit blocks of the loop. Verify this now.
425 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
426 if (!DT->dominates(BB, ExitBlocks[i]))
429 bool MadeChange = false;
430 // Look for store instructions, which may be optimized to memset/memcpy.
433 // Look for a single store which can be optimized into a memset.
434 for (auto &SI : StoreRefsForMemset)
435 MadeChange |= processLoopStore(SI, BECount);
437 // Optimize the store into a memcpy, if it feeds an similarly strided load.
438 for (auto &SI : StoreRefsForMemcpy)
439 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
441 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
442 Instruction *Inst = &*I++;
443 // Look for memset instructions, which may be optimized to a larger memset.
444 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
446 if (!processLoopMemSet(MSI, BECount))
450 // If processing the memset invalidated our iterator, start over from the
461 /// processLoopStore - See if this store can be promoted to a memset.
462 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
463 assert(SI->isSimple() && "Expected only non-volatile stores.");
465 Value *StoredVal = SI->getValueOperand();
466 Value *StorePtr = SI->getPointerOperand();
468 // Check to see if the stride matches the size of the store. If so, then we
469 // know that every byte is touched in the loop.
470 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
471 unsigned Stride = getStoreStride(StoreEv);
472 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
473 if (StoreSize != Stride && StoreSize != -Stride)
476 bool NegStride = StoreSize == -Stride;
478 // See if we can optimize just this store in isolation.
479 return processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
480 StoredVal, SI, StoreEv, BECount, NegStride);
483 /// processLoopMemSet - See if this memset can be promoted to a large memset.
484 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
485 const SCEV *BECount) {
486 // We can only handle non-volatile memsets with a constant size.
487 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
490 // If we're not allowed to hack on memset, we fail.
491 if (!TLI->has(LibFunc::memset))
494 Value *Pointer = MSI->getDest();
496 // See if the pointer expression is an AddRec like {base,+,1} on the current
497 // loop, which indicates a strided store. If we have something else, it's a
498 // random store we can't handle.
499 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
500 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
503 // Reject memsets that are so large that they overflow an unsigned.
504 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
505 if ((SizeInBytes >> 32) != 0)
508 // Check to see if the stride matches the size of the memset. If so, then we
509 // know that every byte is touched in the loop.
510 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
512 // TODO: Could also handle negative stride here someday, that will require the
513 // validity check in mayLoopAccessLocation to be updated though.
514 if (!Stride || MSI->getLength() != Stride->getValue())
517 // Verify that the memset value is loop invariant. If not, we can't promote
519 Value *SplatValue = MSI->getValue();
520 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
523 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
524 MSI->getAlignment(), SplatValue, MSI, Ev,
525 BECount, /*NegStride=*/false);
528 /// mayLoopAccessLocation - Return true if the specified loop might access the
529 /// specified pointer location, which is a loop-strided access. The 'Access'
530 /// argument specifies what the verboten forms of access are (read or write).
531 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
532 const SCEV *BECount, unsigned StoreSize,
534 Instruction *IgnoredStore) {
535 // Get the location that may be stored across the loop. Since the access is
536 // strided positively through memory, we say that the modified location starts
537 // at the pointer and has infinite size.
538 uint64_t AccessSize = MemoryLocation::UnknownSize;
540 // If the loop iterates a fixed number of times, we can refine the access size
541 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
542 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
543 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
545 // TODO: For this to be really effective, we have to dive into the pointer
546 // operand in the store. Store to &A[i] of 100 will always return may alias
547 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
548 // which will then no-alias a store to &A[100].
549 MemoryLocation StoreLoc(Ptr, AccessSize);
551 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
553 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
554 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
560 // If we have a negative stride, Start refers to the end of the memory location
561 // we're trying to memset. Therefore, we need to recompute the base pointer,
562 // which is just Start - BECount*Size.
563 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
564 Type *IntPtr, unsigned StoreSize,
565 ScalarEvolution *SE) {
566 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
568 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
570 return SE->getMinusSCEV(Start, Index);
573 /// processLoopStridedStore - We see a strided store of some value. If we can
574 /// transform this into a memset or memset_pattern in the loop preheader, do so.
575 bool LoopIdiomRecognize::processLoopStridedStore(
576 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
577 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
578 const SCEV *BECount, bool NegStride) {
579 Value *SplatValue = isBytewiseValue(StoredVal);
580 Constant *PatternValue = nullptr;
583 PatternValue = getMemSetPatternValue(StoredVal, DL);
585 assert((SplatValue || PatternValue) &&
586 "Expected either splat value or pattern value.");
588 // The trip count of the loop and the base pointer of the addrec SCEV is
589 // guaranteed to be loop invariant, which means that it should dominate the
590 // header. This allows us to insert code for it in the preheader.
591 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
592 BasicBlock *Preheader = CurLoop->getLoopPreheader();
593 IRBuilder<> Builder(Preheader->getTerminator());
594 SCEVExpander Expander(*SE, *DL, "loop-idiom");
596 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
597 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
599 const SCEV *Start = Ev->getStart();
600 // Handle negative strided loops.
602 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
604 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
605 // this into a memset in the loop preheader now if we want. However, this
606 // would be unsafe to do if there is anything else in the loop that may read
607 // or write to the aliased location. Check for any overlap by generating the
608 // base pointer and checking the region.
610 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
611 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
614 // If we generated new code for the base pointer, clean up.
615 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
619 // Okay, everything looks good, insert the memset.
621 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
622 // pointer size if it isn't already.
623 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
625 const SCEV *NumBytesS =
626 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
627 if (StoreSize != 1) {
628 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
633 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
638 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
640 // Everything is emitted in default address space
641 Type *Int8PtrTy = DestInt8PtrTy;
643 Module *M = TheStore->getModule();
645 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
646 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
648 // Otherwise we should form a memset_pattern16. PatternValue is known to be
649 // an constant array of 16-bytes. Plop the value into a mergable global.
650 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
651 GlobalValue::PrivateLinkage,
652 PatternValue, ".memset_pattern");
653 GV->setUnnamedAddr(true); // Ok to merge these.
654 GV->setAlignment(16);
655 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
656 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
659 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
660 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
661 NewCall->setDebugLoc(TheStore->getDebugLoc());
663 // Okay, the memset has been formed. Zap the original store and anything that
665 deleteDeadInstruction(TheStore, TLI);
670 /// If the stored value is a strided load in the same loop with the same stride
671 /// this may be transformable into a memcpy. This kicks in for stuff like
672 /// for (i) A[i] = B[i];
673 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
674 const SCEV *BECount) {
675 assert(SI->isSimple() && "Expected only non-volatile stores.");
677 Value *StorePtr = SI->getPointerOperand();
678 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
679 unsigned Stride = getStoreStride(StoreEv);
680 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
681 bool NegStride = StoreSize == -Stride;
683 // The store must be feeding a non-volatile load.
684 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
685 assert(LI->isSimple() && "Expected only non-volatile stores.");
687 // See if the pointer expression is an AddRec like {base,+,1} on the current
688 // loop, which indicates a strided load. If we have something else, it's a
689 // random load we can't handle.
690 const SCEVAddRecExpr *LoadEv =
691 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
693 // The trip count of the loop and the base pointer of the addrec SCEV is
694 // guaranteed to be loop invariant, which means that it should dominate the
695 // header. This allows us to insert code for it in the preheader.
696 BasicBlock *Preheader = CurLoop->getLoopPreheader();
697 IRBuilder<> Builder(Preheader->getTerminator());
698 SCEVExpander Expander(*SE, *DL, "loop-idiom");
700 const SCEV *StrStart = StoreEv->getStart();
701 unsigned StrAS = SI->getPointerAddressSpace();
702 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
704 // Handle negative strided loops.
706 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
708 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
709 // this into a memcpy in the loop preheader now if we want. However, this
710 // would be unsafe to do if there is anything else in the loop that may read
711 // or write the memory region we're storing to. This includes the load that
712 // feeds the stores. Check for an alias by generating the base address and
713 // checking everything.
714 Value *StoreBasePtr = Expander.expandCodeFor(
715 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
717 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
718 StoreSize, *AA, SI)) {
720 // If we generated new code for the base pointer, clean up.
721 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
725 const SCEV *LdStart = LoadEv->getStart();
726 unsigned LdAS = LI->getPointerAddressSpace();
728 // Handle negative strided loops.
730 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
732 // For a memcpy, we have to make sure that the input array is not being
733 // mutated by the loop.
734 Value *LoadBasePtr = Expander.expandCodeFor(
735 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
737 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
740 // If we generated new code for the base pointer, clean up.
741 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
742 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
746 // Okay, everything is safe, we can transform this!
748 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
749 // pointer size if it isn't already.
750 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
752 const SCEV *NumBytesS =
753 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
755 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
759 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
762 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
763 std::min(SI->getAlignment(), LI->getAlignment()));
764 NewCall->setDebugLoc(SI->getDebugLoc());
766 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
767 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
768 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
770 // Okay, the memcpy has been formed. Zap the original store and anything that
772 deleteDeadInstruction(SI, TLI);
777 bool LoopIdiomRecognize::runOnNoncountableLoop() {
778 return recognizePopcount();
781 /// Check if the given conditional branch is based on the comparison between
782 /// a variable and zero, and if the variable is non-zero, the control yields to
783 /// the loop entry. If the branch matches the behavior, the variable involved
784 /// in the comparion is returned. This function will be called to see if the
785 /// precondition and postcondition of the loop are in desirable form.
786 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
787 if (!BI || !BI->isConditional())
790 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
794 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
795 if (!CmpZero || !CmpZero->isZero())
798 ICmpInst::Predicate Pred = Cond->getPredicate();
799 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
800 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
801 return Cond->getOperand(0);
806 /// Return true iff the idiom is detected in the loop.
809 /// 1) \p CntInst is set to the instruction counting the population bit.
810 /// 2) \p CntPhi is set to the corresponding phi node.
811 /// 3) \p Var is set to the value whose population bits are being counted.
813 /// The core idiom we are trying to detect is:
816 /// goto loop-exit // the precondition of the loop
819 /// x1 = phi (x0, x2);
820 /// cnt1 = phi(cnt0, cnt2);
824 /// x2 = x1 & (x1 - 1);
830 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
831 Instruction *&CntInst, PHINode *&CntPhi,
833 // step 1: Check to see if the look-back branch match this pattern:
834 // "if (a!=0) goto loop-entry".
835 BasicBlock *LoopEntry;
836 Instruction *DefX2, *CountInst;
837 Value *VarX1, *VarX0;
838 PHINode *PhiX, *CountPhi;
840 DefX2 = CountInst = nullptr;
841 VarX1 = VarX0 = nullptr;
842 PhiX = CountPhi = nullptr;
843 LoopEntry = *(CurLoop->block_begin());
845 // step 1: Check if the loop-back branch is in desirable form.
847 if (Value *T = matchCondition(
848 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
849 DefX2 = dyn_cast<Instruction>(T);
854 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
856 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
859 BinaryOperator *SubOneOp;
861 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
862 VarX1 = DefX2->getOperand(1);
864 VarX1 = DefX2->getOperand(0);
865 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
870 Instruction *SubInst = cast<Instruction>(SubOneOp);
871 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
873 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
874 (SubInst->getOpcode() == Instruction::Add &&
875 Dec->isAllOnesValue()))) {
880 // step 3: Check the recurrence of variable X
882 PhiX = dyn_cast<PHINode>(VarX1);
884 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
889 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
892 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
893 IterE = LoopEntry->end();
894 Iter != IterE; Iter++) {
895 Instruction *Inst = &*Iter;
896 if (Inst->getOpcode() != Instruction::Add)
899 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
900 if (!Inc || !Inc->isOne())
903 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
904 if (!Phi || Phi->getParent() != LoopEntry)
907 // Check if the result of the instruction is live of the loop.
908 bool LiveOutLoop = false;
909 for (User *U : Inst->users()) {
910 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
927 // step 5: check if the precondition is in this form:
928 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
930 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
931 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
932 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
943 /// Recognizes a population count idiom in a non-countable loop.
945 /// If detected, transforms the relevant code to issue the popcount intrinsic
946 /// function call, and returns true; otherwise, returns false.
947 bool LoopIdiomRecognize::recognizePopcount() {
948 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
951 // Counting population are usually conducted by few arithmetic instructions.
952 // Such instructions can be easily "absorbed" by vacant slots in a
953 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
954 // in a compact loop.
956 // Give up if the loop has multiple blocks or multiple backedges.
957 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
960 BasicBlock *LoopBody = *(CurLoop->block_begin());
961 if (LoopBody->size() >= 20) {
962 // The loop is too big, bail out.
966 // It should have a preheader containing nothing but an unconditional branch.
967 BasicBlock *PH = CurLoop->getLoopPreheader();
970 if (&PH->front() != PH->getTerminator())
972 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
973 if (!EntryBI || EntryBI->isConditional())
976 // It should have a precondition block where the generated popcount instrinsic
977 // function can be inserted.
978 auto *PreCondBB = PH->getSinglePredecessor();
981 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
982 if (!PreCondBI || PreCondBI->isUnconditional())
985 Instruction *CntInst;
988 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
991 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
995 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
997 Value *Ops[] = {Val};
998 Type *Tys[] = {Val->getType()};
1000 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1001 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1002 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1003 CI->setDebugLoc(DL);
1008 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1009 Instruction *CntInst,
1010 PHINode *CntPhi, Value *Var) {
1011 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1012 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1013 const DebugLoc DL = CntInst->getDebugLoc();
1015 // Assuming before transformation, the loop is following:
1016 // if (x) // the precondition
1017 // do { cnt++; x &= x - 1; } while(x);
1019 // Step 1: Insert the ctpop instruction at the end of the precondition block
1020 IRBuilder<> Builder(PreCondBr);
1021 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1023 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1024 NewCount = PopCntZext =
1025 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1027 if (NewCount != PopCnt)
1028 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1030 // TripCnt is exactly the number of iterations the loop has
1033 // If the population counter's initial value is not zero, insert Add Inst.
1034 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1035 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1036 if (!InitConst || !InitConst->isZero()) {
1037 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1038 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1042 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1043 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1044 // function would be partial dead code, and downstream passes will drag
1045 // it back from the precondition block to the preheader.
1047 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1049 Value *Opnd0 = PopCntZext;
1050 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1051 if (PreCond->getOperand(0) != Var)
1052 std::swap(Opnd0, Opnd1);
1054 ICmpInst *NewPreCond = cast<ICmpInst>(
1055 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1056 PreCondBr->setCondition(NewPreCond);
1058 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1061 // Step 3: Note that the population count is exactly the trip count of the
1062 // loop in question, which enable us to to convert the loop from noncountable
1063 // loop into a countable one. The benefit is twofold:
1065 // - If the loop only counts population, the entire loop becomes dead after
1066 // the transformation. It is a lot easier to prove a countable loop dead
1067 // than to prove a noncountable one. (In some C dialects, an infinite loop
1068 // isn't dead even if it computes nothing useful. In general, DCE needs
1069 // to prove a noncountable loop finite before safely delete it.)
1071 // - If the loop also performs something else, it remains alive.
1072 // Since it is transformed to countable form, it can be aggressively
1073 // optimized by some optimizations which are in general not applicable
1074 // to a noncountable loop.
1076 // After this step, this loop (conceptually) would look like following:
1077 // newcnt = __builtin_ctpop(x);
1080 // do { cnt++; x &= x-1; t--) } while (t > 0);
1081 BasicBlock *Body = *(CurLoop->block_begin());
1083 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1084 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1085 Type *Ty = TripCnt->getType();
1087 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1089 Builder.SetInsertPoint(LbCond);
1090 Instruction *TcDec = cast<Instruction>(
1091 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1092 "tcdec", false, true));
1094 TcPhi->addIncoming(TripCnt, PreHead);
1095 TcPhi->addIncoming(TcDec, Body);
1097 CmpInst::Predicate Pred =
1098 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1099 LbCond->setPredicate(Pred);
1100 LbCond->setOperand(0, TcDec);
1101 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1104 // Step 4: All the references to the original population counter outside
1105 // the loop are replaced with the NewCount -- the value returned from
1106 // __builtin_ctpop().
1107 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1109 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1110 // loop. The loop would otherwise not be deleted even if it becomes empty.
1111 SE->forgetLoop(CurLoop);