1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass implements an idiom recognizer that transforms simple loops into a 11 // non-loop form. In cases that this kicks in, it can be a significant 12 // performance win. 13 // 14 // If compiling for code size we avoid idiom recognition if the resulting 15 // code could be larger than the code for the original loop. One way this could 16 // happen is if the loop is not removable after idiom recognition due to the 17 // presence of non-idiom instructions. The initial implementation of the 18 // heuristics applies to idioms in multi-block loops. 19 // 20 //===----------------------------------------------------------------------===// 21 // 22 // TODO List: 23 // 24 // Future loop memory idioms to recognize: 25 // memcmp, memmove, strlen, etc. 26 // Future floating point idioms to recognize in -ffast-math mode: 27 // fpowi 28 // Future integer operation idioms to recognize: 29 // ctpop, ctlz, cttz 30 // 31 // Beware that isel's default lowering for ctpop is highly inefficient for 32 // i64 and larger types when i64 is legal and the value has few bits set. It 33 // would be good to enhance isel to emit a loop for ctpop in this case. 34 // 35 // This could recognize common matrix multiplies and dot product idioms and 36 // replace them with calls to BLAS (if linked in??). 37 // 38 //===----------------------------------------------------------------------===// 39 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/LoopPassManager.h" 50 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 51 #include "llvm/Analysis/ScalarEvolutionExpander.h" 52 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 53 #include "llvm/Analysis/TargetLibraryInfo.h" 54 #include "llvm/Analysis/TargetTransformInfo.h" 55 #include "llvm/Analysis/ValueTracking.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/IRBuilder.h" 59 #include "llvm/IR/IntrinsicInst.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Transforms/Scalar.h" 64 #include "llvm/Transforms/Utils/BuildLibCalls.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include "llvm/Transforms/Utils/LoopUtils.h" 67 using namespace llvm; 68 69 #define DEBUG_TYPE "loop-idiom" 70 71 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 72 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 73 74 static cl::opt<bool> UseLIRCodeSizeHeurs( 75 "use-lir-code-size-heurs", 76 cl::desc("Use loop idiom recognition code size heuristics when compiling" 77 "with -Os/-Oz"), 78 cl::init(true), cl::Hidden); 79 80 namespace { 81 82 class LoopIdiomRecognize { 83 Loop *CurLoop; 84 AliasAnalysis *AA; 85 DominatorTree *DT; 86 LoopInfo *LI; 87 ScalarEvolution *SE; 88 TargetLibraryInfo *TLI; 89 const TargetTransformInfo *TTI; 90 const DataLayout *DL; 91 bool ApplyCodeSizeHeuristics; 92 93 public: 94 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 95 LoopInfo *LI, ScalarEvolution *SE, 96 TargetLibraryInfo *TLI, 97 const TargetTransformInfo *TTI, 98 const DataLayout *DL) 99 : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), 100 DL(DL) {} 101 102 bool runOnLoop(Loop *L); 103 104 private: 105 typedef SmallVector<StoreInst *, 8> StoreList; 106 typedef MapVector<Value *, StoreList> StoreListMap; 107 StoreListMap StoreRefsForMemset; 108 StoreListMap StoreRefsForMemsetPattern; 109 StoreList StoreRefsForMemcpy; 110 bool HasMemset; 111 bool HasMemsetPattern; 112 bool HasMemcpy; 113 114 /// \name Countable Loop Idiom Handling 115 /// @{ 116 117 bool runOnCountableLoop(); 118 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 119 SmallVectorImpl<BasicBlock *> &ExitBlocks); 120 121 void collectStores(BasicBlock *BB); 122 bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern, 123 bool &ForMemcpy); 124 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, 125 bool ForMemset); 126 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 127 128 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, 129 unsigned StoreAlignment, Value *StoredVal, 130 Instruction *TheStore, 131 SmallPtrSetImpl<Instruction *> &Stores, 132 const SCEVAddRecExpr *Ev, const SCEV *BECount, 133 bool NegStride, bool IsLoopMemset = false); 134 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); 135 bool avoidLIRForMultiBlockLoop(bool IsMemset = false, 136 bool IsLoopMemset = false); 137 138 /// @} 139 /// \name Noncountable Loop Idiom Handling 140 /// @{ 141 142 bool runOnNoncountableLoop(); 143 144 bool recognizePopcount(); 145 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 146 PHINode *CntPhi, Value *Var); 147 148 /// @} 149 }; 150 151 class LoopIdiomRecognizeLegacyPass : public LoopPass { 152 public: 153 static char ID; 154 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 155 initializeLoopIdiomRecognizeLegacyPassPass( 156 *PassRegistry::getPassRegistry()); 157 } 158 159 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 160 if (skipLoop(L)) 161 return false; 162 163 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 164 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 165 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 166 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 167 TargetLibraryInfo *TLI = 168 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 169 const TargetTransformInfo *TTI = 170 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 171 *L->getHeader()->getParent()); 172 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); 173 174 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL); 175 return LIR.runOnLoop(L); 176 } 177 178 /// This transformation requires natural loop information & requires that 179 /// loop preheaders be inserted into the CFG. 180 /// 181 void getAnalysisUsage(AnalysisUsage &AU) const override { 182 AU.addRequired<TargetLibraryInfoWrapperPass>(); 183 AU.addRequired<TargetTransformInfoWrapperPass>(); 184 getLoopAnalysisUsage(AU); 185 } 186 }; 187 } // End anonymous namespace. 188 189 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, 190 LoopAnalysisManager &AM) { 191 const auto &FAM = 192 AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager(); 193 Function *F = L.getHeader()->getParent(); 194 195 // Use getCachedResult because Loop pass cannot trigger a function analysis. 196 auto *AA = FAM.getCachedResult<AAManager>(*F); 197 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F); 198 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F); 199 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F); 200 auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F); 201 const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F); 202 const auto *DL = &L.getHeader()->getModule()->getDataLayout(); 203 assert((AA && DT && LI && SE && TLI && TTI && DL) && 204 "Analyses for Loop Idiom Recognition not available"); 205 206 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL); 207 if (!LIR.runOnLoop(&L)) 208 return PreservedAnalyses::all(); 209 210 return getLoopPassPreservedAnalyses(); 211 } 212 213 char LoopIdiomRecognizeLegacyPass::ID = 0; 214 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", 215 "Recognize loop idioms", false, false) 216 INITIALIZE_PASS_DEPENDENCY(LoopPass) 217 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 218 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 219 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", 220 "Recognize loop idioms", false, false) 221 222 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } 223 224 static void deleteDeadInstruction(Instruction *I) { 225 I->replaceAllUsesWith(UndefValue::get(I->getType())); 226 I->eraseFromParent(); 227 } 228 229 //===----------------------------------------------------------------------===// 230 // 231 // Implementation of LoopIdiomRecognize 232 // 233 //===----------------------------------------------------------------------===// 234 235 bool LoopIdiomRecognize::runOnLoop(Loop *L) { 236 CurLoop = L; 237 // If the loop could not be converted to canonical form, it must have an 238 // indirectbr in it, just give up. 239 if (!L->getLoopPreheader()) 240 return false; 241 242 // Disable loop idiom recognition if the function's name is a common idiom. 243 StringRef Name = L->getHeader()->getParent()->getName(); 244 if (Name == "memset" || Name == "memcpy") 245 return false; 246 247 // Determine if code size heuristics need to be applied. 248 ApplyCodeSizeHeuristics = 249 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs; 250 251 HasMemset = TLI->has(LibFunc::memset); 252 HasMemsetPattern = TLI->has(LibFunc::memset_pattern16); 253 HasMemcpy = TLI->has(LibFunc::memcpy); 254 255 if (HasMemset || HasMemsetPattern || HasMemcpy) 256 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 257 return runOnCountableLoop(); 258 259 return runOnNoncountableLoop(); 260 } 261 262 bool LoopIdiomRecognize::runOnCountableLoop() { 263 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 264 assert(!isa<SCEVCouldNotCompute>(BECount) && 265 "runOnCountableLoop() called on a loop without a predictable" 266 "backedge-taken count"); 267 268 // If this loop executes exactly one time, then it should be peeled, not 269 // optimized by this pass. 270 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 271 if (BECst->getAPInt() == 0) 272 return false; 273 274 SmallVector<BasicBlock *, 8> ExitBlocks; 275 CurLoop->getUniqueExitBlocks(ExitBlocks); 276 277 DEBUG(dbgs() << "loop-idiom Scanning: F[" 278 << CurLoop->getHeader()->getParent()->getName() << "] Loop %" 279 << CurLoop->getHeader()->getName() << "\n"); 280 281 bool MadeChange = false; 282 283 // The following transforms hoist stores/memsets into the loop pre-header. 284 // Give up if the loop has instructions may throw. 285 LoopSafetyInfo SafetyInfo; 286 computeLoopSafetyInfo(&SafetyInfo, CurLoop); 287 if (SafetyInfo.MayThrow) 288 return MadeChange; 289 290 // Scan all the blocks in the loop that are not in subloops. 291 for (auto *BB : CurLoop->getBlocks()) { 292 // Ignore blocks in subloops. 293 if (LI->getLoopFor(BB) != CurLoop) 294 continue; 295 296 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 297 } 298 return MadeChange; 299 } 300 301 static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) { 302 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 303 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) && 304 "Don't overflow unsigned."); 305 return (unsigned)SizeInBits >> 3; 306 } 307 308 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { 309 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 310 return ConstStride->getAPInt(); 311 } 312 313 /// getMemSetPatternValue - If a strided store of the specified value is safe to 314 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 315 /// be passed in. Otherwise, return null. 316 /// 317 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 318 /// just replicate their input array and then pass on to memset_pattern16. 319 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 320 // If the value isn't a constant, we can't promote it to being in a constant 321 // array. We could theoretically do a store to an alloca or something, but 322 // that doesn't seem worthwhile. 323 Constant *C = dyn_cast<Constant>(V); 324 if (!C) 325 return nullptr; 326 327 // Only handle simple values that are a power of two bytes in size. 328 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 329 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 330 return nullptr; 331 332 // Don't care enough about darwin/ppc to implement this. 333 if (DL->isBigEndian()) 334 return nullptr; 335 336 // Convert to size in bytes. 337 Size /= 8; 338 339 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 340 // if the top and bottom are the same (e.g. for vectors and large integers). 341 if (Size > 16) 342 return nullptr; 343 344 // If the constant is exactly 16 bytes, just use it. 345 if (Size == 16) 346 return C; 347 348 // Otherwise, we'll use an array of the constants. 349 unsigned ArraySize = 16 / Size; 350 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 351 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 352 } 353 354 bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset, 355 bool &ForMemsetPattern, bool &ForMemcpy) { 356 // Don't touch volatile stores. 357 if (!SI->isSimple()) 358 return false; 359 360 // Avoid merging nontemporal stores. 361 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 362 return false; 363 364 Value *StoredVal = SI->getValueOperand(); 365 Value *StorePtr = SI->getPointerOperand(); 366 367 // Reject stores that are so large that they overflow an unsigned. 368 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 369 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) 370 return false; 371 372 // See if the pointer expression is an AddRec like {base,+,1} on the current 373 // loop, which indicates a strided store. If we have something else, it's a 374 // random store we can't handle. 375 const SCEVAddRecExpr *StoreEv = 376 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 377 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 378 return false; 379 380 // Check to see if we have a constant stride. 381 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 382 return false; 383 384 // See if the store can be turned into a memset. 385 386 // If the stored value is a byte-wise value (like i32 -1), then it may be 387 // turned into a memset of i8 -1, assuming that all the consecutive bytes 388 // are stored. A store of i32 0x01020304 can never be turned into a memset, 389 // but it can be turned into memset_pattern if the target supports it. 390 Value *SplatValue = isBytewiseValue(StoredVal); 391 Constant *PatternValue = nullptr; 392 393 // If we're allowed to form a memset, and the stored value would be 394 // acceptable for memset, use it. 395 if (HasMemset && SplatValue && 396 // Verify that the stored value is loop invariant. If not, we can't 397 // promote the memset. 398 CurLoop->isLoopInvariant(SplatValue)) { 399 // It looks like we can use SplatValue. 400 ForMemset = true; 401 return true; 402 } else if (HasMemsetPattern && 403 // Don't create memset_pattern16s with address spaces. 404 StorePtr->getType()->getPointerAddressSpace() == 0 && 405 (PatternValue = getMemSetPatternValue(StoredVal, DL))) { 406 // It looks like we can use PatternValue! 407 ForMemsetPattern = true; 408 return true; 409 } 410 411 // Otherwise, see if the store can be turned into a memcpy. 412 if (HasMemcpy) { 413 // Check to see if the stride matches the size of the store. If so, then we 414 // know that every byte is touched in the loop. 415 APInt Stride = getStoreStride(StoreEv); 416 unsigned StoreSize = getStoreSizeInBytes(SI, DL); 417 if (StoreSize != Stride && StoreSize != -Stride) 418 return false; 419 420 // The store must be feeding a non-volatile load. 421 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 422 if (!LI || !LI->isSimple()) 423 return false; 424 425 // See if the pointer expression is an AddRec like {base,+,1} on the current 426 // loop, which indicates a strided load. If we have something else, it's a 427 // random load we can't handle. 428 const SCEVAddRecExpr *LoadEv = 429 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 430 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 431 return false; 432 433 // The store and load must share the same stride. 434 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 435 return false; 436 437 // Success. This store can be converted into a memcpy. 438 ForMemcpy = true; 439 return true; 440 } 441 // This store can't be transformed into a memset/memcpy. 442 return false; 443 } 444 445 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 446 StoreRefsForMemset.clear(); 447 StoreRefsForMemsetPattern.clear(); 448 StoreRefsForMemcpy.clear(); 449 for (Instruction &I : *BB) { 450 StoreInst *SI = dyn_cast<StoreInst>(&I); 451 if (!SI) 452 continue; 453 454 bool ForMemset = false; 455 bool ForMemsetPattern = false; 456 bool ForMemcpy = false; 457 // Make sure this is a strided store with a constant stride. 458 if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy)) 459 continue; 460 461 // Save the store locations. 462 if (ForMemset) { 463 // Find the base pointer. 464 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 465 StoreRefsForMemset[Ptr].push_back(SI); 466 } else if (ForMemsetPattern) { 467 // Find the base pointer. 468 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 469 StoreRefsForMemsetPattern[Ptr].push_back(SI); 470 } else if (ForMemcpy) 471 StoreRefsForMemcpy.push_back(SI); 472 } 473 } 474 475 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 476 /// with the specified backedge count. This block is known to be in the current 477 /// loop and not in any subloops. 478 bool LoopIdiomRecognize::runOnLoopBlock( 479 BasicBlock *BB, const SCEV *BECount, 480 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 481 // We can only promote stores in this block if they are unconditionally 482 // executed in the loop. For a block to be unconditionally executed, it has 483 // to dominate all the exit blocks of the loop. Verify this now. 484 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 485 if (!DT->dominates(BB, ExitBlocks[i])) 486 return false; 487 488 bool MadeChange = false; 489 // Look for store instructions, which may be optimized to memset/memcpy. 490 collectStores(BB); 491 492 // Look for a single store or sets of stores with a common base, which can be 493 // optimized into a memset (memset_pattern). The latter most commonly happens 494 // with structs and handunrolled loops. 495 for (auto &SL : StoreRefsForMemset) 496 MadeChange |= processLoopStores(SL.second, BECount, true); 497 498 for (auto &SL : StoreRefsForMemsetPattern) 499 MadeChange |= processLoopStores(SL.second, BECount, false); 500 501 // Optimize the store into a memcpy, if it feeds an similarly strided load. 502 for (auto &SI : StoreRefsForMemcpy) 503 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 504 505 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 506 Instruction *Inst = &*I++; 507 // Look for memset instructions, which may be optimized to a larger memset. 508 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { 509 WeakVH InstPtr(&*I); 510 if (!processLoopMemSet(MSI, BECount)) 511 continue; 512 MadeChange = true; 513 514 // If processing the memset invalidated our iterator, start over from the 515 // top of the block. 516 if (!InstPtr) 517 I = BB->begin(); 518 continue; 519 } 520 } 521 522 return MadeChange; 523 } 524 525 /// processLoopStores - See if this store(s) can be promoted to a memset. 526 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, 527 const SCEV *BECount, 528 bool ForMemset) { 529 // Try to find consecutive stores that can be transformed into memsets. 530 SetVector<StoreInst *> Heads, Tails; 531 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 532 533 // Do a quadratic search on all of the given stores and find 534 // all of the pairs of stores that follow each other. 535 SmallVector<unsigned, 16> IndexQueue; 536 for (unsigned i = 0, e = SL.size(); i < e; ++i) { 537 assert(SL[i]->isSimple() && "Expected only non-volatile stores."); 538 539 Value *FirstStoredVal = SL[i]->getValueOperand(); 540 Value *FirstStorePtr = SL[i]->getPointerOperand(); 541 const SCEVAddRecExpr *FirstStoreEv = 542 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); 543 APInt FirstStride = getStoreStride(FirstStoreEv); 544 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL); 545 546 // See if we can optimize just this store in isolation. 547 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { 548 Heads.insert(SL[i]); 549 continue; 550 } 551 552 Value *FirstSplatValue = nullptr; 553 Constant *FirstPatternValue = nullptr; 554 555 if (ForMemset) 556 FirstSplatValue = isBytewiseValue(FirstStoredVal); 557 else 558 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); 559 560 assert((FirstSplatValue || FirstPatternValue) && 561 "Expected either splat value or pattern value."); 562 563 IndexQueue.clear(); 564 // If a store has multiple consecutive store candidates, search Stores 565 // array according to the sequence: from i+1 to e, then from i-1 to 0. 566 // This is because usually pairing with immediate succeeding or preceding 567 // candidate create the best chance to find memset opportunity. 568 unsigned j = 0; 569 for (j = i + 1; j < e; ++j) 570 IndexQueue.push_back(j); 571 for (j = i; j > 0; --j) 572 IndexQueue.push_back(j - 1); 573 574 for (auto &k : IndexQueue) { 575 assert(SL[k]->isSimple() && "Expected only non-volatile stores."); 576 Value *SecondStorePtr = SL[k]->getPointerOperand(); 577 const SCEVAddRecExpr *SecondStoreEv = 578 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); 579 APInt SecondStride = getStoreStride(SecondStoreEv); 580 581 if (FirstStride != SecondStride) 582 continue; 583 584 Value *SecondStoredVal = SL[k]->getValueOperand(); 585 Value *SecondSplatValue = nullptr; 586 Constant *SecondPatternValue = nullptr; 587 588 if (ForMemset) 589 SecondSplatValue = isBytewiseValue(SecondStoredVal); 590 else 591 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); 592 593 assert((SecondSplatValue || SecondPatternValue) && 594 "Expected either splat value or pattern value."); 595 596 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { 597 if (ForMemset) { 598 if (FirstSplatValue != SecondSplatValue) 599 continue; 600 } else { 601 if (FirstPatternValue != SecondPatternValue) 602 continue; 603 } 604 Tails.insert(SL[k]); 605 Heads.insert(SL[i]); 606 ConsecutiveChain[SL[i]] = SL[k]; 607 break; 608 } 609 } 610 } 611 612 // We may run into multiple chains that merge into a single chain. We mark the 613 // stores that we transformed so that we don't visit the same store twice. 614 SmallPtrSet<Value *, 16> TransformedStores; 615 bool Changed = false; 616 617 // For stores that start but don't end a link in the chain: 618 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 619 it != e; ++it) { 620 if (Tails.count(*it)) 621 continue; 622 623 // We found a store instr that starts a chain. Now follow the chain and try 624 // to transform it. 625 SmallPtrSet<Instruction *, 8> AdjacentStores; 626 StoreInst *I = *it; 627 628 StoreInst *HeadStore = I; 629 unsigned StoreSize = 0; 630 631 // Collect the chain into a list. 632 while (Tails.count(I) || Heads.count(I)) { 633 if (TransformedStores.count(I)) 634 break; 635 AdjacentStores.insert(I); 636 637 StoreSize += getStoreSizeInBytes(I, DL); 638 // Move to the next value in the chain. 639 I = ConsecutiveChain[I]; 640 } 641 642 Value *StoredVal = HeadStore->getValueOperand(); 643 Value *StorePtr = HeadStore->getPointerOperand(); 644 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 645 APInt Stride = getStoreStride(StoreEv); 646 647 // Check to see if the stride matches the size of the stores. If so, then 648 // we know that every byte is touched in the loop. 649 if (StoreSize != Stride && StoreSize != -Stride) 650 continue; 651 652 bool NegStride = StoreSize == -Stride; 653 654 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(), 655 StoredVal, HeadStore, AdjacentStores, StoreEv, 656 BECount, NegStride)) { 657 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); 658 Changed = true; 659 } 660 } 661 662 return Changed; 663 } 664 665 /// processLoopMemSet - See if this memset can be promoted to a large memset. 666 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 667 const SCEV *BECount) { 668 // We can only handle non-volatile memsets with a constant size. 669 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) 670 return false; 671 672 // If we're not allowed to hack on memset, we fail. 673 if (!HasMemset) 674 return false; 675 676 Value *Pointer = MSI->getDest(); 677 678 // See if the pointer expression is an AddRec like {base,+,1} on the current 679 // loop, which indicates a strided store. If we have something else, it's a 680 // random store we can't handle. 681 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 682 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) 683 return false; 684 685 // Reject memsets that are so large that they overflow an unsigned. 686 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 687 if ((SizeInBytes >> 32) != 0) 688 return false; 689 690 // Check to see if the stride matches the size of the memset. If so, then we 691 // know that every byte is touched in the loop. 692 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 693 if (!ConstStride) 694 return false; 695 696 APInt Stride = ConstStride->getAPInt(); 697 if (SizeInBytes != Stride && SizeInBytes != -Stride) 698 return false; 699 700 // Verify that the memset value is loop invariant. If not, we can't promote 701 // the memset. 702 Value *SplatValue = MSI->getValue(); 703 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 704 return false; 705 706 SmallPtrSet<Instruction *, 1> MSIs; 707 MSIs.insert(MSI); 708 bool NegStride = SizeInBytes == -Stride; 709 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, 710 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev, 711 BECount, NegStride, /*IsLoopMemset=*/true); 712 } 713 714 /// mayLoopAccessLocation - Return true if the specified loop might access the 715 /// specified pointer location, which is a loop-strided access. The 'Access' 716 /// argument specifies what the verboten forms of access are (read or write). 717 static bool 718 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 719 const SCEV *BECount, unsigned StoreSize, 720 AliasAnalysis &AA, 721 SmallPtrSetImpl<Instruction *> &IgnoredStores) { 722 // Get the location that may be stored across the loop. Since the access is 723 // strided positively through memory, we say that the modified location starts 724 // at the pointer and has infinite size. 725 uint64_t AccessSize = MemoryLocation::UnknownSize; 726 727 // If the loop iterates a fixed number of times, we can refine the access size 728 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 729 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 730 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize; 731 732 // TODO: For this to be really effective, we have to dive into the pointer 733 // operand in the store. Store to &A[i] of 100 will always return may alias 734 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 735 // which will then no-alias a store to &A[100]. 736 MemoryLocation StoreLoc(Ptr, AccessSize); 737 738 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 739 ++BI) 740 for (Instruction &I : **BI) 741 if (IgnoredStores.count(&I) == 0 && 742 (AA.getModRefInfo(&I, StoreLoc) & Access)) 743 return true; 744 745 return false; 746 } 747 748 // If we have a negative stride, Start refers to the end of the memory location 749 // we're trying to memset. Therefore, we need to recompute the base pointer, 750 // which is just Start - BECount*Size. 751 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, 752 Type *IntPtr, unsigned StoreSize, 753 ScalarEvolution *SE) { 754 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 755 if (StoreSize != 1) 756 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), 757 SCEV::FlagNUW); 758 return SE->getMinusSCEV(Start, Index); 759 } 760 761 /// processLoopStridedStore - We see a strided store of some value. If we can 762 /// transform this into a memset or memset_pattern in the loop preheader, do so. 763 bool LoopIdiomRecognize::processLoopStridedStore( 764 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment, 765 Value *StoredVal, Instruction *TheStore, 766 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, 767 const SCEV *BECount, bool NegStride, bool IsLoopMemset) { 768 Value *SplatValue = isBytewiseValue(StoredVal); 769 Constant *PatternValue = nullptr; 770 771 if (!SplatValue) 772 PatternValue = getMemSetPatternValue(StoredVal, DL); 773 774 assert((SplatValue || PatternValue) && 775 "Expected either splat value or pattern value."); 776 777 // The trip count of the loop and the base pointer of the addrec SCEV is 778 // guaranteed to be loop invariant, which means that it should dominate the 779 // header. This allows us to insert code for it in the preheader. 780 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 781 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 782 IRBuilder<> Builder(Preheader->getTerminator()); 783 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 784 785 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 786 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); 787 788 const SCEV *Start = Ev->getStart(); 789 // Handle negative strided loops. 790 if (NegStride) 791 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE); 792 793 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 794 // this into a memset in the loop preheader now if we want. However, this 795 // would be unsafe to do if there is anything else in the loop that may read 796 // or write to the aliased location. Check for any overlap by generating the 797 // base pointer and checking the region. 798 Value *BasePtr = 799 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 800 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize, 801 *AA, Stores)) { 802 Expander.clear(); 803 // If we generated new code for the base pointer, clean up. 804 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); 805 return false; 806 } 807 808 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) 809 return false; 810 811 // Okay, everything looks good, insert the memset. 812 813 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 814 // pointer size if it isn't already. 815 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); 816 817 const SCEV *NumBytesS = 818 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW); 819 if (StoreSize != 1) { 820 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), 821 SCEV::FlagNUW); 822 } 823 824 Value *NumBytes = 825 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); 826 827 CallInst *NewCall; 828 if (SplatValue) { 829 NewCall = 830 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); 831 } else { 832 // Everything is emitted in default address space 833 Type *Int8PtrTy = DestInt8PtrTy; 834 835 Module *M = TheStore->getModule(); 836 Value *MSP = 837 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(), 838 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr); 839 inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI); 840 841 // Otherwise we should form a memset_pattern16. PatternValue is known to be 842 // an constant array of 16-bytes. Plop the value into a mergable global. 843 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 844 GlobalValue::PrivateLinkage, 845 PatternValue, ".memset_pattern"); 846 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. 847 GV->setAlignment(16); 848 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 849 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 850 } 851 852 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 853 << " from store to: " << *Ev << " at: " << *TheStore << "\n"); 854 NewCall->setDebugLoc(TheStore->getDebugLoc()); 855 856 // Okay, the memset has been formed. Zap the original store and anything that 857 // feeds into it. 858 for (auto *I : Stores) 859 deleteDeadInstruction(I); 860 ++NumMemSet; 861 return true; 862 } 863 864 /// If the stored value is a strided load in the same loop with the same stride 865 /// this may be transformable into a memcpy. This kicks in for stuff like 866 /// for (i) A[i] = B[i]; 867 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, 868 const SCEV *BECount) { 869 assert(SI->isSimple() && "Expected only non-volatile stores."); 870 871 Value *StorePtr = SI->getPointerOperand(); 872 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 873 APInt Stride = getStoreStride(StoreEv); 874 unsigned StoreSize = getStoreSizeInBytes(SI, DL); 875 bool NegStride = StoreSize == -Stride; 876 877 // The store must be feeding a non-volatile load. 878 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 879 assert(LI->isSimple() && "Expected only non-volatile stores."); 880 881 // See if the pointer expression is an AddRec like {base,+,1} on the current 882 // loop, which indicates a strided load. If we have something else, it's a 883 // random load we can't handle. 884 const SCEVAddRecExpr *LoadEv = 885 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 886 887 // The trip count of the loop and the base pointer of the addrec SCEV is 888 // guaranteed to be loop invariant, which means that it should dominate the 889 // header. This allows us to insert code for it in the preheader. 890 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 891 IRBuilder<> Builder(Preheader->getTerminator()); 892 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 893 894 const SCEV *StrStart = StoreEv->getStart(); 895 unsigned StrAS = SI->getPointerAddressSpace(); 896 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS); 897 898 // Handle negative strided loops. 899 if (NegStride) 900 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE); 901 902 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 903 // this into a memcpy in the loop preheader now if we want. However, this 904 // would be unsafe to do if there is anything else in the loop that may read 905 // or write the memory region we're storing to. This includes the load that 906 // feeds the stores. Check for an alias by generating the base address and 907 // checking everything. 908 Value *StoreBasePtr = Expander.expandCodeFor( 909 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); 910 911 SmallPtrSet<Instruction *, 1> Stores; 912 Stores.insert(SI); 913 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount, 914 StoreSize, *AA, Stores)) { 915 Expander.clear(); 916 // If we generated new code for the base pointer, clean up. 917 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 918 return false; 919 } 920 921 const SCEV *LdStart = LoadEv->getStart(); 922 unsigned LdAS = LI->getPointerAddressSpace(); 923 924 // Handle negative strided loops. 925 if (NegStride) 926 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE); 927 928 // For a memcpy, we have to make sure that the input array is not being 929 // mutated by the loop. 930 Value *LoadBasePtr = Expander.expandCodeFor( 931 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); 932 933 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize, 934 *AA, Stores)) { 935 Expander.clear(); 936 // If we generated new code for the base pointer, clean up. 937 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); 938 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 939 return false; 940 } 941 942 if (avoidLIRForMultiBlockLoop()) 943 return false; 944 945 // Okay, everything is safe, we can transform this! 946 947 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 948 // pointer size if it isn't already. 949 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); 950 951 const SCEV *NumBytesS = 952 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); 953 if (StoreSize != 1) 954 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), 955 SCEV::FlagNUW); 956 957 Value *NumBytes = 958 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); 959 960 CallInst *NewCall = 961 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, 962 std::min(SI->getAlignment(), LI->getAlignment())); 963 NewCall->setDebugLoc(SI->getDebugLoc()); 964 965 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" 966 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 967 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); 968 969 // Okay, the memcpy has been formed. Zap the original store and anything that 970 // feeds into it. 971 deleteDeadInstruction(SI); 972 ++NumMemCpy; 973 return true; 974 } 975 976 // When compiling for codesize we avoid idiom recognition for a multi-block loop 977 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. 978 // 979 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, 980 bool IsLoopMemset) { 981 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { 982 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) { 983 DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() 984 << " : LIR " << (IsMemset ? "Memset" : "Memcpy") 985 << " avoided: multi-block top-level loop\n"); 986 return true; 987 } 988 } 989 990 return false; 991 } 992 993 bool LoopIdiomRecognize::runOnNoncountableLoop() { 994 return recognizePopcount(); 995 } 996 997 /// Check if the given conditional branch is based on the comparison between 998 /// a variable and zero, and if the variable is non-zero, the control yields to 999 /// the loop entry. If the branch matches the behavior, the variable involved 1000 /// in the comparion is returned. This function will be called to see if the 1001 /// precondition and postcondition of the loop are in desirable form. 1002 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) { 1003 if (!BI || !BI->isConditional()) 1004 return nullptr; 1005 1006 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1007 if (!Cond) 1008 return nullptr; 1009 1010 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 1011 if (!CmpZero || !CmpZero->isZero()) 1012 return nullptr; 1013 1014 ICmpInst::Predicate Pred = Cond->getPredicate(); 1015 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) || 1016 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry)) 1017 return Cond->getOperand(0); 1018 1019 return nullptr; 1020 } 1021 1022 /// Return true iff the idiom is detected in the loop. 1023 /// 1024 /// Additionally: 1025 /// 1) \p CntInst is set to the instruction counting the population bit. 1026 /// 2) \p CntPhi is set to the corresponding phi node. 1027 /// 3) \p Var is set to the value whose population bits are being counted. 1028 /// 1029 /// The core idiom we are trying to detect is: 1030 /// \code 1031 /// if (x0 != 0) 1032 /// goto loop-exit // the precondition of the loop 1033 /// cnt0 = init-val; 1034 /// do { 1035 /// x1 = phi (x0, x2); 1036 /// cnt1 = phi(cnt0, cnt2); 1037 /// 1038 /// cnt2 = cnt1 + 1; 1039 /// ... 1040 /// x2 = x1 & (x1 - 1); 1041 /// ... 1042 /// } while(x != 0); 1043 /// 1044 /// loop-exit: 1045 /// \endcode 1046 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 1047 Instruction *&CntInst, PHINode *&CntPhi, 1048 Value *&Var) { 1049 // step 1: Check to see if the look-back branch match this pattern: 1050 // "if (a!=0) goto loop-entry". 1051 BasicBlock *LoopEntry; 1052 Instruction *DefX2, *CountInst; 1053 Value *VarX1, *VarX0; 1054 PHINode *PhiX, *CountPhi; 1055 1056 DefX2 = CountInst = nullptr; 1057 VarX1 = VarX0 = nullptr; 1058 PhiX = CountPhi = nullptr; 1059 LoopEntry = *(CurLoop->block_begin()); 1060 1061 // step 1: Check if the loop-back branch is in desirable form. 1062 { 1063 if (Value *T = matchCondition( 1064 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1065 DefX2 = dyn_cast<Instruction>(T); 1066 else 1067 return false; 1068 } 1069 1070 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 1071 { 1072 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 1073 return false; 1074 1075 BinaryOperator *SubOneOp; 1076 1077 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 1078 VarX1 = DefX2->getOperand(1); 1079 else { 1080 VarX1 = DefX2->getOperand(0); 1081 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 1082 } 1083 if (!SubOneOp) 1084 return false; 1085 1086 Instruction *SubInst = cast<Instruction>(SubOneOp); 1087 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); 1088 if (!Dec || 1089 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || 1090 (SubInst->getOpcode() == Instruction::Add && 1091 Dec->isAllOnesValue()))) { 1092 return false; 1093 } 1094 } 1095 1096 // step 3: Check the recurrence of variable X 1097 { 1098 PhiX = dyn_cast<PHINode>(VarX1); 1099 if (!PhiX || 1100 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { 1101 return false; 1102 } 1103 } 1104 1105 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 1106 { 1107 CountInst = nullptr; 1108 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1109 IterE = LoopEntry->end(); 1110 Iter != IterE; Iter++) { 1111 Instruction *Inst = &*Iter; 1112 if (Inst->getOpcode() != Instruction::Add) 1113 continue; 1114 1115 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1116 if (!Inc || !Inc->isOne()) 1117 continue; 1118 1119 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); 1120 if (!Phi || Phi->getParent() != LoopEntry) 1121 continue; 1122 1123 // Check if the result of the instruction is live of the loop. 1124 bool LiveOutLoop = false; 1125 for (User *U : Inst->users()) { 1126 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 1127 LiveOutLoop = true; 1128 break; 1129 } 1130 } 1131 1132 if (LiveOutLoop) { 1133 CountInst = Inst; 1134 CountPhi = Phi; 1135 break; 1136 } 1137 } 1138 1139 if (!CountInst) 1140 return false; 1141 } 1142 1143 // step 5: check if the precondition is in this form: 1144 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 1145 { 1146 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1147 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 1148 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 1149 return false; 1150 1151 CntInst = CountInst; 1152 CntPhi = CountPhi; 1153 Var = T; 1154 } 1155 1156 return true; 1157 } 1158 1159 /// Recognizes a population count idiom in a non-countable loop. 1160 /// 1161 /// If detected, transforms the relevant code to issue the popcount intrinsic 1162 /// function call, and returns true; otherwise, returns false. 1163 bool LoopIdiomRecognize::recognizePopcount() { 1164 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 1165 return false; 1166 1167 // Counting population are usually conducted by few arithmetic instructions. 1168 // Such instructions can be easily "absorbed" by vacant slots in a 1169 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 1170 // in a compact loop. 1171 1172 // Give up if the loop has multiple blocks or multiple backedges. 1173 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1174 return false; 1175 1176 BasicBlock *LoopBody = *(CurLoop->block_begin()); 1177 if (LoopBody->size() >= 20) { 1178 // The loop is too big, bail out. 1179 return false; 1180 } 1181 1182 // It should have a preheader containing nothing but an unconditional branch. 1183 BasicBlock *PH = CurLoop->getLoopPreheader(); 1184 if (!PH || &PH->front() != PH->getTerminator()) 1185 return false; 1186 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 1187 if (!EntryBI || EntryBI->isConditional()) 1188 return false; 1189 1190 // It should have a precondition block where the generated popcount instrinsic 1191 // function can be inserted. 1192 auto *PreCondBB = PH->getSinglePredecessor(); 1193 if (!PreCondBB) 1194 return false; 1195 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1196 if (!PreCondBI || PreCondBI->isUnconditional()) 1197 return false; 1198 1199 Instruction *CntInst; 1200 PHINode *CntPhi; 1201 Value *Val; 1202 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 1203 return false; 1204 1205 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 1206 return true; 1207 } 1208 1209 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1210 const DebugLoc &DL) { 1211 Value *Ops[] = {Val}; 1212 Type *Tys[] = {Val->getType()}; 1213 1214 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1215 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 1216 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1217 CI->setDebugLoc(DL); 1218 1219 return CI; 1220 } 1221 1222 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 1223 Instruction *CntInst, 1224 PHINode *CntPhi, Value *Var) { 1225 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 1226 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1227 const DebugLoc DL = CntInst->getDebugLoc(); 1228 1229 // Assuming before transformation, the loop is following: 1230 // if (x) // the precondition 1231 // do { cnt++; x &= x - 1; } while(x); 1232 1233 // Step 1: Insert the ctpop instruction at the end of the precondition block 1234 IRBuilder<> Builder(PreCondBr); 1235 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 1236 { 1237 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 1238 NewCount = PopCntZext = 1239 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 1240 1241 if (NewCount != PopCnt) 1242 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1243 1244 // TripCnt is exactly the number of iterations the loop has 1245 TripCnt = NewCount; 1246 1247 // If the population counter's initial value is not zero, insert Add Inst. 1248 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 1249 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 1250 if (!InitConst || !InitConst->isZero()) { 1251 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 1252 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1253 } 1254 } 1255 1256 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 1257 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 1258 // function would be partial dead code, and downstream passes will drag 1259 // it back from the precondition block to the preheader. 1260 { 1261 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 1262 1263 Value *Opnd0 = PopCntZext; 1264 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 1265 if (PreCond->getOperand(0) != Var) 1266 std::swap(Opnd0, Opnd1); 1267 1268 ICmpInst *NewPreCond = cast<ICmpInst>( 1269 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 1270 PreCondBr->setCondition(NewPreCond); 1271 1272 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 1273 } 1274 1275 // Step 3: Note that the population count is exactly the trip count of the 1276 // loop in question, which enable us to to convert the loop from noncountable 1277 // loop into a countable one. The benefit is twofold: 1278 // 1279 // - If the loop only counts population, the entire loop becomes dead after 1280 // the transformation. It is a lot easier to prove a countable loop dead 1281 // than to prove a noncountable one. (In some C dialects, an infinite loop 1282 // isn't dead even if it computes nothing useful. In general, DCE needs 1283 // to prove a noncountable loop finite before safely delete it.) 1284 // 1285 // - If the loop also performs something else, it remains alive. 1286 // Since it is transformed to countable form, it can be aggressively 1287 // optimized by some optimizations which are in general not applicable 1288 // to a noncountable loop. 1289 // 1290 // After this step, this loop (conceptually) would look like following: 1291 // newcnt = __builtin_ctpop(x); 1292 // t = newcnt; 1293 // if (x) 1294 // do { cnt++; x &= x-1; t--) } while (t > 0); 1295 BasicBlock *Body = *(CurLoop->block_begin()); 1296 { 1297 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); 1298 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1299 Type *Ty = TripCnt->getType(); 1300 1301 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1302 1303 Builder.SetInsertPoint(LbCond); 1304 Instruction *TcDec = cast<Instruction>( 1305 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1306 "tcdec", false, true)); 1307 1308 TcPhi->addIncoming(TripCnt, PreHead); 1309 TcPhi->addIncoming(TcDec, Body); 1310 1311 CmpInst::Predicate Pred = 1312 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 1313 LbCond->setPredicate(Pred); 1314 LbCond->setOperand(0, TcDec); 1315 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1316 } 1317 1318 // Step 4: All the references to the original population counter outside 1319 // the loop are replaced with the NewCount -- the value returned from 1320 // __builtin_ctpop(). 1321 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1322 1323 // step 5: Forget the "non-computable" trip-count SCEV associated with the 1324 // loop. The loop would otherwise not be deleted even if it becomes empty. 1325 SE->forgetLoop(CurLoop); 1326 } 1327