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 //===----------------------------------------------------------------------===// 15 // 16 // TODO List: 17 // 18 // Future loop memory idioms to recognize: 19 // memcmp, memmove, strlen, etc. 20 // Future floating point idioms to recognize in -ffast-math mode: 21 // fpowi 22 // Future integer operation idioms to recognize: 23 // ctpop, ctlz, cttz 24 // 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. 28 // 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; } 33 // 34 // This could recognize common matrix multiplies and dot product idioms and 35 // replace them with calls to BLAS (if linked in??). 36 // 37 //===----------------------------------------------------------------------===// 38 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" 59 using namespace llvm; 60 61 #define DEBUG_TYPE "loop-idiom" 62 63 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 64 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 65 66 namespace { 67 68 class LoopIdiomRecognize : public LoopPass { 69 Loop *CurLoop; 70 AliasAnalysis *AA; 71 DominatorTree *DT; 72 LoopInfo *LI; 73 ScalarEvolution *SE; 74 TargetLibraryInfo *TLI; 75 const TargetTransformInfo *TTI; 76 const DataLayout *DL; 77 78 public: 79 static char ID; 80 explicit LoopIdiomRecognize() : LoopPass(ID) { 81 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); 82 } 83 84 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 85 86 /// This transformation requires natural loop information & requires that 87 /// loop preheaders be inserted into the CFG. 88 /// 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>(); 107 } 108 109 private: 110 typedef SmallVector<StoreInst *, 8> StoreList; 111 StoreList StoreRefsForMemset; 112 StoreList StoreRefsForMemcpy; 113 bool HasMemset; 114 bool HasMemsetPattern; 115 bool HasMemcpy; 116 117 /// \name Countable Loop Idiom Handling 118 /// @{ 119 120 bool runOnCountableLoop(); 121 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 122 SmallVectorImpl<BasicBlock *> &ExitBlocks); 123 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); 128 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); 134 135 /// @} 136 /// \name Noncountable Loop Idiom Handling 137 /// @{ 138 139 bool runOnNoncountableLoop(); 140 141 bool recognizePopcount(); 142 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 143 PHINode *CntPhi, Value *Var); 144 145 /// @} 146 }; 147 148 } // End anonymous namespace. 149 150 char LoopIdiomRecognize::ID = 0; 151 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", 152 false, false) 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", 165 false, false) 166 167 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } 168 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. 172 /// 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); 180 } 181 182 //===----------------------------------------------------------------------===// 183 // 184 // Implementation of LoopIdiomRecognize 185 // 186 //===----------------------------------------------------------------------===// 187 188 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { 189 if (skipOptnoneFunction(L)) 190 return false; 191 192 CurLoop = 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()) 196 return false; 197 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") 201 return false; 202 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(); 211 212 HasMemset = TLI->has(LibFunc::memset); 213 HasMemsetPattern = TLI->has(LibFunc::memset_pattern16); 214 HasMemcpy = TLI->has(LibFunc::memcpy); 215 216 if (HasMemset || HasMemsetPattern || HasMemcpy) 217 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 218 return runOnCountableLoop(); 219 220 return runOnNoncountableLoop(); 221 } 222 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"); 228 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) 233 return false; 234 235 SmallVector<BasicBlock *, 8> ExitBlocks; 236 CurLoop->getUniqueExitBlocks(ExitBlocks); 237 238 DEBUG(dbgs() << "loop-idiom Scanning: F[" 239 << CurLoop->getHeader()->getParent()->getName() << "] Loop %" 240 << CurLoop->getHeader()->getName() << "\n"); 241 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) 247 continue; 248 249 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 250 } 251 return MadeChange; 252 } 253 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; 259 } 260 261 static unsigned getStoreStride(const SCEVAddRecExpr *StoreEv) { 262 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 263 return ConstStride->getAPInt().getZExtValue(); 264 } 265 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. 269 /// 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); 277 if (!C) 278 return nullptr; 279 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))) 283 return nullptr; 284 285 // Don't care enough about darwin/ppc to implement this. 286 if (DL->isBigEndian()) 287 return nullptr; 288 289 // Convert to size in bytes. 290 Size /= 8; 291 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). 294 if (Size > 16) 295 return nullptr; 296 297 // If the constant is exactly 16 bytes, just use it. 298 if (Size == 16) 299 return C; 300 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)); 305 } 306 307 bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset, 308 bool &ForMemcpy) { 309 // Don't touch volatile stores. 310 if (!SI->isSimple()) 311 return false; 312 313 Value *StoredVal = SI->getValueOperand(); 314 Value *StorePtr = SI->getPointerOperand(); 315 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) 319 return false; 320 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()) 327 return false; 328 329 // Check to see if we have a constant stride. 330 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 331 return false; 332 333 // See if the store can be turned into a memset. 334 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; 341 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. 349 ForMemset = true; 350 return true; 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! 356 ForMemset = true; 357 return true; 358 } 359 360 // Otherwise, see if the store can be turned into a memcpy. 361 if (HasMemcpy) { 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) 367 return false; 368 369 // The store must be feeding a non-volatile load. 370 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 371 if (!LI || !LI->isSimple()) 372 return false; 373 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()) 380 return false; 381 382 // The store and load must share the same stride. 383 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 384 return false; 385 386 // Success. This store can be converted into a memcpy. 387 ForMemcpy = true; 388 return true; 389 } 390 // This store can't be transformed into a memset/memcpy. 391 return false; 392 } 393 394 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 395 StoreRefsForMemset.clear(); 396 StoreRefsForMemcpy.clear(); 397 for (Instruction &I : *BB) { 398 StoreInst *SI = dyn_cast<StoreInst>(&I); 399 if (!SI) 400 continue; 401 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)) 406 continue; 407 408 // Save the store locations. 409 if (ForMemset) 410 StoreRefsForMemset.push_back(SI); 411 else if (ForMemcpy) 412 StoreRefsForMemcpy.push_back(SI); 413 } 414 } 415 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])) 427 return false; 428 429 bool MadeChange = false; 430 // Look for store instructions, which may be optimized to memset/memcpy. 431 collectStores(BB); 432 433 // Look for a single store which can be optimized into a memset. 434 for (auto &SI : StoreRefsForMemset) 435 MadeChange |= processLoopStore(SI, BECount); 436 437 // Optimize the store into a memcpy, if it feeds an similarly strided load. 438 for (auto &SI : StoreRefsForMemcpy) 439 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 440 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)) { 445 WeakVH InstPtr(&*I); 446 if (!processLoopMemSet(MSI, BECount)) 447 continue; 448 MadeChange = true; 449 450 // If processing the memset invalidated our iterator, start over from the 451 // top of the block. 452 if (!InstPtr) 453 I = BB->begin(); 454 continue; 455 } 456 } 457 458 return MadeChange; 459 } 460 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."); 464 465 Value *StoredVal = SI->getValueOperand(); 466 Value *StorePtr = SI->getPointerOperand(); 467 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) 474 return false; 475 476 bool NegStride = StoreSize == -Stride; 477 478 // See if we can optimize just this store in isolation. 479 return processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(), 480 StoredVal, SI, StoreEv, BECount, NegStride); 481 } 482 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())) 488 return false; 489 490 // If we're not allowed to hack on memset, we fail. 491 if (!TLI->has(LibFunc::memset)) 492 return false; 493 494 Value *Pointer = MSI->getDest(); 495 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()) 501 return false; 502 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) 506 return false; 507 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)); 511 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()) 515 return false; 516 517 // Verify that the memset value is loop invariant. If not, we can't promote 518 // the memset. 519 Value *SplatValue = MSI->getValue(); 520 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 521 return false; 522 523 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, 524 MSI->getAlignment(), SplatValue, MSI, Ev, 525 BECount, /*NegStride=*/false); 526 } 527 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, 533 AliasAnalysis &AA, 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; 539 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; 544 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); 550 551 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 552 ++BI) 553 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) 554 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access)) 555 return true; 556 557 return false; 558 } 559 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); 567 if (StoreSize != 1) 568 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), 569 SCEV::FlagNUW); 570 return SE->getMinusSCEV(Start, Index); 571 } 572 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; 581 582 if (!SplatValue) 583 PatternValue = getMemSetPatternValue(StoredVal, DL); 584 585 assert((SplatValue || PatternValue) && 586 "Expected either splat value or pattern value."); 587 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"); 595 596 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 597 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); 598 599 const SCEV *Start = Ev->getStart(); 600 // Handle negative strided loops. 601 if (NegStride) 602 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE); 603 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. 609 Value *BasePtr = 610 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 611 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize, 612 *AA, TheStore)) { 613 Expander.clear(); 614 // If we generated new code for the base pointer, clean up. 615 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); 616 return false; 617 } 618 619 // Okay, everything looks good, insert the memset. 620 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); 624 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), 629 SCEV::FlagNUW); 630 } 631 632 Value *NumBytes = 633 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); 634 635 CallInst *NewCall; 636 if (SplatValue) { 637 NewCall = 638 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); 639 } else { 640 // Everything is emitted in default address space 641 Type *Int8PtrTy = DestInt8PtrTy; 642 643 Module *M = TheStore->getModule(); 644 Value *MSP = 645 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(), 646 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr); 647 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}); 657 } 658 659 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 660 << " from store to: " << *Ev << " at: " << *TheStore << "\n"); 661 NewCall->setDebugLoc(TheStore->getDebugLoc()); 662 663 // Okay, the memset has been formed. Zap the original store and anything that 664 // feeds into it. 665 deleteDeadInstruction(TheStore, TLI); 666 ++NumMemSet; 667 return true; 668 } 669 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."); 676 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; 682 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."); 686 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())); 692 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"); 699 700 const SCEV *StrStart = StoreEv->getStart(); 701 unsigned StrAS = SI->getPointerAddressSpace(); 702 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS); 703 704 // Handle negative strided loops. 705 if (NegStride) 706 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE); 707 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()); 716 717 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount, 718 StoreSize, *AA, SI)) { 719 Expander.clear(); 720 // If we generated new code for the base pointer, clean up. 721 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 722 return false; 723 } 724 725 const SCEV *LdStart = LoadEv->getStart(); 726 unsigned LdAS = LI->getPointerAddressSpace(); 727 728 // Handle negative strided loops. 729 if (NegStride) 730 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE); 731 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()); 736 737 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize, 738 *AA, SI)) { 739 Expander.clear(); 740 // If we generated new code for the base pointer, clean up. 741 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); 742 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 743 return false; 744 } 745 746 // Okay, everything is safe, we can transform this! 747 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); 751 752 const SCEV *NumBytesS = 753 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); 754 if (StoreSize != 1) 755 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), 756 SCEV::FlagNUW); 757 758 Value *NumBytes = 759 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); 760 761 CallInst *NewCall = 762 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, 763 std::min(SI->getAlignment(), LI->getAlignment())); 764 NewCall->setDebugLoc(SI->getDebugLoc()); 765 766 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" 767 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 768 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); 769 770 // Okay, the memcpy has been formed. Zap the original store and anything that 771 // feeds into it. 772 deleteDeadInstruction(SI, TLI); 773 ++NumMemCpy; 774 return true; 775 } 776 777 bool LoopIdiomRecognize::runOnNoncountableLoop() { 778 return recognizePopcount(); 779 } 780 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()) 788 return nullptr; 789 790 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 791 if (!Cond) 792 return nullptr; 793 794 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 795 if (!CmpZero || !CmpZero->isZero()) 796 return nullptr; 797 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); 802 803 return nullptr; 804 } 805 806 /// Return true iff the idiom is detected in the loop. 807 /// 808 /// Additionally: 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. 812 /// 813 /// The core idiom we are trying to detect is: 814 /// \code 815 /// if (x0 != 0) 816 /// goto loop-exit // the precondition of the loop 817 /// cnt0 = init-val; 818 /// do { 819 /// x1 = phi (x0, x2); 820 /// cnt1 = phi(cnt0, cnt2); 821 /// 822 /// cnt2 = cnt1 + 1; 823 /// ... 824 /// x2 = x1 & (x1 - 1); 825 /// ... 826 /// } while(x != 0); 827 /// 828 /// loop-exit: 829 /// \endcode 830 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 831 Instruction *&CntInst, PHINode *&CntPhi, 832 Value *&Var) { 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; 839 840 DefX2 = CountInst = nullptr; 841 VarX1 = VarX0 = nullptr; 842 PhiX = CountPhi = nullptr; 843 LoopEntry = *(CurLoop->block_begin()); 844 845 // step 1: Check if the loop-back branch is in desirable form. 846 { 847 if (Value *T = matchCondition( 848 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 849 DefX2 = dyn_cast<Instruction>(T); 850 else 851 return false; 852 } 853 854 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 855 { 856 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 857 return false; 858 859 BinaryOperator *SubOneOp; 860 861 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 862 VarX1 = DefX2->getOperand(1); 863 else { 864 VarX1 = DefX2->getOperand(0); 865 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 866 } 867 if (!SubOneOp) 868 return false; 869 870 Instruction *SubInst = cast<Instruction>(SubOneOp); 871 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); 872 if (!Dec || 873 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || 874 (SubInst->getOpcode() == Instruction::Add && 875 Dec->isAllOnesValue()))) { 876 return false; 877 } 878 } 879 880 // step 3: Check the recurrence of variable X 881 { 882 PhiX = dyn_cast<PHINode>(VarX1); 883 if (!PhiX || 884 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { 885 return false; 886 } 887 } 888 889 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 890 { 891 CountInst = nullptr; 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) 897 continue; 898 899 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 900 if (!Inc || !Inc->isOne()) 901 continue; 902 903 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); 904 if (!Phi || Phi->getParent() != LoopEntry) 905 continue; 906 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) { 911 LiveOutLoop = true; 912 break; 913 } 914 } 915 916 if (LiveOutLoop) { 917 CountInst = Inst; 918 CountPhi = Phi; 919 break; 920 } 921 } 922 923 if (!CountInst) 924 return false; 925 } 926 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;" 929 { 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)) 933 return false; 934 935 CntInst = CountInst; 936 CntPhi = CountPhi; 937 Var = T; 938 } 939 940 return true; 941 } 942 943 /// Recognizes a population count idiom in a non-countable loop. 944 /// 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) 949 return false; 950 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. 955 956 // Give up if the loop has multiple blocks or multiple backedges. 957 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 958 return false; 959 960 BasicBlock *LoopBody = *(CurLoop->block_begin()); 961 if (LoopBody->size() >= 20) { 962 // The loop is too big, bail out. 963 return false; 964 } 965 966 // It should have a preheader containing nothing but an unconditional branch. 967 BasicBlock *PH = CurLoop->getLoopPreheader(); 968 if (!PH) 969 return false; 970 if (&PH->front() != PH->getTerminator()) 971 return false; 972 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 973 if (!EntryBI || EntryBI->isConditional()) 974 return false; 975 976 // It should have a precondition block where the generated popcount instrinsic 977 // function can be inserted. 978 auto *PreCondBB = PH->getSinglePredecessor(); 979 if (!PreCondBB) 980 return false; 981 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 982 if (!PreCondBI || PreCondBI->isUnconditional()) 983 return false; 984 985 Instruction *CntInst; 986 PHINode *CntPhi; 987 Value *Val; 988 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 989 return false; 990 991 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 992 return true; 993 } 994 995 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 996 DebugLoc DL) { 997 Value *Ops[] = {Val}; 998 Type *Tys[] = {Val->getType()}; 999 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); 1004 1005 return CI; 1006 } 1007 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(); 1014 1015 // Assuming before transformation, the loop is following: 1016 // if (x) // the precondition 1017 // do { cnt++; x &= x - 1; } while(x); 1018 1019 // Step 1: Insert the ctpop instruction at the end of the precondition block 1020 IRBuilder<> Builder(PreCondBr); 1021 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 1022 { 1023 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 1024 NewCount = PopCntZext = 1025 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 1026 1027 if (NewCount != PopCnt) 1028 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1029 1030 // TripCnt is exactly the number of iterations the loop has 1031 TripCnt = NewCount; 1032 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); 1039 } 1040 } 1041 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. 1046 { 1047 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 1048 1049 Value *Opnd0 = PopCntZext; 1050 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 1051 if (PreCond->getOperand(0) != Var) 1052 std::swap(Opnd0, Opnd1); 1053 1054 ICmpInst *NewPreCond = cast<ICmpInst>( 1055 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 1056 PreCondBr->setCondition(NewPreCond); 1057 1058 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 1059 } 1060 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: 1064 // 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.) 1070 // 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. 1075 // 1076 // After this step, this loop (conceptually) would look like following: 1077 // newcnt = __builtin_ctpop(x); 1078 // t = newcnt; 1079 // if (x) 1080 // do { cnt++; x &= x-1; t--) } while (t > 0); 1081 BasicBlock *Body = *(CurLoop->block_begin()); 1082 { 1083 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); 1084 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1085 Type *Ty = TripCnt->getType(); 1086 1087 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1088 1089 Builder.SetInsertPoint(LbCond); 1090 Instruction *TcDec = cast<Instruction>( 1091 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1092 "tcdec", false, true)); 1093 1094 TcPhi->addIncoming(TripCnt, PreHead); 1095 TcPhi->addIncoming(TcDec, Body); 1096 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)); 1102 } 1103 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); 1108 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); 1112 } 1113