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/ScalarEvolutionExpander.h" 46 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.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 StoreRefs; 112 113 /// \name Countable Loop Idiom Handling 114 /// @{ 115 116 bool runOnCountableLoop(); 117 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 118 SmallVectorImpl<BasicBlock *> &ExitBlocks); 119 120 void collectStores(BasicBlock *BB); 121 bool processLoopStore(StoreInst *SI, const SCEV *BECount); 122 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 123 124 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, 125 unsigned StoreAlignment, Value *SplatValue, 126 Instruction *TheStore, const SCEVAddRecExpr *Ev, 127 const SCEV *BECount, bool NegStride); 128 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize, 129 const SCEVAddRecExpr *StoreEv, 130 const SCEVAddRecExpr *LoadEv, 131 const SCEV *BECount); 132 133 /// @} 134 /// \name Noncountable Loop Idiom Handling 135 /// @{ 136 137 bool runOnNoncountableLoop(); 138 139 bool recognizePopcount(); 140 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 141 PHINode *CntPhi, Value *Var); 142 143 /// @} 144 }; 145 146 } // End anonymous namespace. 147 148 char LoopIdiomRecognize::ID = 0; 149 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", 150 false, false) 151 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 152 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 153 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 154 INITIALIZE_PASS_DEPENDENCY(LCSSA) 155 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 156 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 157 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 158 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 159 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 160 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 161 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 162 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", 163 false, false) 164 165 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } 166 167 /// deleteDeadInstruction - Delete this instruction. Before we do, go through 168 /// and zero out all the operands of this instruction. If any of them become 169 /// dead, delete them and the computation tree that feeds them. 170 /// 171 static void deleteDeadInstruction(Instruction *I, 172 const TargetLibraryInfo *TLI) { 173 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end()); 174 I->replaceAllUsesWith(UndefValue::get(I->getType())); 175 I->eraseFromParent(); 176 for (Value *Op : Operands) 177 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI); 178 } 179 180 //===----------------------------------------------------------------------===// 181 // 182 // Implementation of LoopIdiomRecognize 183 // 184 //===----------------------------------------------------------------------===// 185 186 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { 187 if (skipOptnoneFunction(L)) 188 return false; 189 190 CurLoop = L; 191 // If the loop could not be converted to canonical form, it must have an 192 // indirectbr in it, just give up. 193 if (!L->getLoopPreheader()) 194 return false; 195 196 // Disable loop idiom recognition if the function's name is a common idiom. 197 StringRef Name = L->getHeader()->getParent()->getName(); 198 if (Name == "memset" || Name == "memcpy") 199 return false; 200 201 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 202 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 203 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 204 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 205 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 206 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 207 *CurLoop->getHeader()->getParent()); 208 DL = &CurLoop->getHeader()->getModule()->getDataLayout(); 209 210 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 211 return runOnCountableLoop(); 212 213 return runOnNoncountableLoop(); 214 } 215 216 bool LoopIdiomRecognize::runOnCountableLoop() { 217 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 218 assert(!isa<SCEVCouldNotCompute>(BECount) && 219 "runOnCountableLoop() called on a loop without a predictable" 220 "backedge-taken count"); 221 222 // If this loop executes exactly one time, then it should be peeled, not 223 // optimized by this pass. 224 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 225 if (BECst->getValue()->getValue() == 0) 226 return false; 227 228 SmallVector<BasicBlock *, 8> ExitBlocks; 229 CurLoop->getUniqueExitBlocks(ExitBlocks); 230 231 DEBUG(dbgs() << "loop-idiom Scanning: F[" 232 << CurLoop->getHeader()->getParent()->getName() << "] Loop %" 233 << CurLoop->getHeader()->getName() << "\n"); 234 235 bool MadeChange = false; 236 // Scan all the blocks in the loop that are not in subloops. 237 for (auto *BB : CurLoop->getBlocks()) { 238 // Ignore blocks in subloops. 239 if (LI->getLoopFor(BB) != CurLoop) 240 continue; 241 242 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 243 } 244 return MadeChange; 245 } 246 247 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 248 StoreRefs.clear(); 249 for (Instruction &I : *BB) { 250 StoreInst *SI = dyn_cast<StoreInst>(&I); 251 if (!SI) 252 continue; 253 254 // Don't touch volatile stores. 255 if (!SI->isSimple()) 256 continue; 257 258 // Save the store locations. 259 StoreRefs.push_back(SI); 260 } 261 } 262 263 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 264 /// with the specified backedge count. This block is known to be in the current 265 /// loop and not in any subloops. 266 bool LoopIdiomRecognize::runOnLoopBlock( 267 BasicBlock *BB, const SCEV *BECount, 268 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 269 // We can only promote stores in this block if they are unconditionally 270 // executed in the loop. For a block to be unconditionally executed, it has 271 // to dominate all the exit blocks of the loop. Verify this now. 272 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 273 if (!DT->dominates(BB, ExitBlocks[i])) 274 return false; 275 276 bool MadeChange = false; 277 // Look for store instructions, which may be optimized to memset/memcpy. 278 collectStores(BB); 279 for (auto &SI : StoreRefs) 280 MadeChange |= processLoopStore(SI, BECount); 281 282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 283 Instruction *Inst = &*I++; 284 // Look for memset instructions, which may be optimized to a larger memset. 285 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { 286 WeakVH InstPtr(&*I); 287 if (!processLoopMemSet(MSI, BECount)) 288 continue; 289 MadeChange = true; 290 291 // If processing the memset invalidated our iterator, start over from the 292 // top of the block. 293 if (!InstPtr) 294 I = BB->begin(); 295 continue; 296 } 297 } 298 299 return MadeChange; 300 } 301 302 /// processLoopStore - See if this store can be promoted to a memset or memcpy. 303 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) { 304 assert(SI->isSimple() && "Expected only non-volatile stores."); 305 306 Value *StoredVal = SI->getValueOperand(); 307 Value *StorePtr = SI->getPointerOperand(); 308 309 // Reject stores that are so large that they overflow an unsigned. 310 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 311 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) 312 return false; 313 314 // See if the pointer expression is an AddRec like {base,+,1} on the current 315 // loop, which indicates a strided store. If we have something else, it's a 316 // random store we can't handle. 317 const SCEVAddRecExpr *StoreEv = 318 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 319 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 320 return false; 321 322 // Check to see if the stride matches the size of the store. If so, then we 323 // know that every byte is touched in the loop. 324 unsigned StoreSize = (unsigned)SizeInBits >> 3; 325 326 const SCEVConstant *ConstStride = 327 dyn_cast<SCEVConstant>(StoreEv->getOperand(1)); 328 if (!ConstStride) 329 return false; 330 331 APInt Stride = ConstStride->getValue()->getValue(); 332 if (StoreSize != Stride && StoreSize != -Stride) 333 return false; 334 335 bool NegStride = StoreSize == -Stride; 336 337 // See if we can optimize just this store in isolation. 338 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(), 339 StoredVal, SI, StoreEv, BECount, NegStride)) 340 return true; 341 342 // TODO: We don't handle negative stride memcpys. 343 if (NegStride) 344 return false; 345 346 // If the stored value is a strided load in the same loop with the same stride 347 // this may be transformable into a memcpy. This kicks in for stuff like 348 // for (i) A[i] = B[i]; 349 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 350 const SCEVAddRecExpr *LoadEv = 351 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0))); 352 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() && 353 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple()) 354 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount)) 355 return true; 356 } 357 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n"; 358 359 return false; 360 } 361 362 /// processLoopMemSet - See if this memset can be promoted to a large memset. 363 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 364 const SCEV *BECount) { 365 // We can only handle non-volatile memsets with a constant size. 366 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) 367 return false; 368 369 // If we're not allowed to hack on memset, we fail. 370 if (!TLI->has(LibFunc::memset)) 371 return false; 372 373 Value *Pointer = MSI->getDest(); 374 375 // See if the pointer expression is an AddRec like {base,+,1} on the current 376 // loop, which indicates a strided store. If we have something else, it's a 377 // random store we can't handle. 378 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 379 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) 380 return false; 381 382 // Reject memsets that are so large that they overflow an unsigned. 383 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 384 if ((SizeInBytes >> 32) != 0) 385 return false; 386 387 // Check to see if the stride matches the size of the memset. If so, then we 388 // know that every byte is touched in the loop. 389 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 390 391 // TODO: Could also handle negative stride here someday, that will require the 392 // validity check in mayLoopAccessLocation to be updated though. 393 if (!Stride || MSI->getLength() != Stride->getValue()) 394 return false; 395 396 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, 397 MSI->getAlignment(), MSI->getValue(), MSI, Ev, 398 BECount, /*NegStride=*/false); 399 } 400 401 /// mayLoopAccessLocation - Return true if the specified loop might access the 402 /// specified pointer location, which is a loop-strided access. The 'Access' 403 /// argument specifies what the verboten forms of access are (read or write). 404 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 405 const SCEV *BECount, unsigned StoreSize, 406 AliasAnalysis &AA, 407 Instruction *IgnoredStore) { 408 // Get the location that may be stored across the loop. Since the access is 409 // strided positively through memory, we say that the modified location starts 410 // at the pointer and has infinite size. 411 uint64_t AccessSize = MemoryLocation::UnknownSize; 412 413 // If the loop iterates a fixed number of times, we can refine the access size 414 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 415 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 416 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize; 417 418 // TODO: For this to be really effective, we have to dive into the pointer 419 // operand in the store. Store to &A[i] of 100 will always return may alias 420 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 421 // which will then no-alias a store to &A[100]. 422 MemoryLocation StoreLoc(Ptr, AccessSize); 423 424 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 425 ++BI) 426 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) 427 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access)) 428 return true; 429 430 return false; 431 } 432 433 /// getMemSetPatternValue - If a strided store of the specified value is safe to 434 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 435 /// be passed in. Otherwise, return null. 436 /// 437 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 438 /// just replicate their input array and then pass on to memset_pattern16. 439 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 440 // If the value isn't a constant, we can't promote it to being in a constant 441 // array. We could theoretically do a store to an alloca or something, but 442 // that doesn't seem worthwhile. 443 Constant *C = dyn_cast<Constant>(V); 444 if (!C) 445 return nullptr; 446 447 // Only handle simple values that are a power of two bytes in size. 448 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 449 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 450 return nullptr; 451 452 // Don't care enough about darwin/ppc to implement this. 453 if (DL->isBigEndian()) 454 return nullptr; 455 456 // Convert to size in bytes. 457 Size /= 8; 458 459 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 460 // if the top and bottom are the same (e.g. for vectors and large integers). 461 if (Size > 16) 462 return nullptr; 463 464 // If the constant is exactly 16 bytes, just use it. 465 if (Size == 16) 466 return C; 467 468 // Otherwise, we'll use an array of the constants. 469 unsigned ArraySize = 16 / Size; 470 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 471 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 472 } 473 474 /// processLoopStridedStore - We see a strided store of some value. If we can 475 /// transform this into a memset or memset_pattern in the loop preheader, do so. 476 bool LoopIdiomRecognize::processLoopStridedStore( 477 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment, 478 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev, 479 const SCEV *BECount, bool NegStride) { 480 481 // If the stored value is a byte-wise value (like i32 -1), then it may be 482 // turned into a memset of i8 -1, assuming that all the consecutive bytes 483 // are stored. A store of i32 0x01020304 can never be turned into a memset, 484 // but it can be turned into memset_pattern if the target supports it. 485 Value *SplatValue = isBytewiseValue(StoredVal); 486 Constant *PatternValue = nullptr; 487 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 488 489 // If we're allowed to form a memset, and the stored value would be acceptable 490 // for memset, use it. 491 if (SplatValue && TLI->has(LibFunc::memset) && 492 // Verify that the stored value is loop invariant. If not, we can't 493 // promote the memset. 494 CurLoop->isLoopInvariant(SplatValue)) { 495 // Keep and use SplatValue. 496 PatternValue = nullptr; 497 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) && 498 (PatternValue = getMemSetPatternValue(StoredVal, DL))) { 499 // Don't create memset_pattern16s with address spaces. 500 // It looks like we can use PatternValue! 501 SplatValue = nullptr; 502 } else { 503 // Otherwise, this isn't an idiom we can transform. For example, we can't 504 // do anything with a 3-byte store. 505 return false; 506 } 507 508 // The trip count of the loop and the base pointer of the addrec SCEV is 509 // guaranteed to be loop invariant, which means that it should dominate the 510 // header. This allows us to insert code for it in the preheader. 511 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 512 IRBuilder<> Builder(Preheader->getTerminator()); 513 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 514 515 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 516 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); 517 518 const SCEV *Start = Ev->getStart(); 519 // If we have a negative stride, Start refers to the end of the memory 520 // location we're trying to memset. Therefore, we need to recompute the start 521 // point, which is just Start - BECount*Size. 522 if (NegStride) { 523 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 524 if (StoreSize != 1) 525 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), 526 SCEV::FlagNUW); 527 Start = SE->getMinusSCEV(Ev->getStart(), Index); 528 } 529 530 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 531 // this into a memset in the loop preheader now if we want. However, this 532 // would be unsafe to do if there is anything else in the loop that may read 533 // or write to the aliased location. Check for any overlap by generating the 534 // base pointer and checking the region. 535 Value *BasePtr = 536 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 537 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize, 538 *AA, TheStore)) { 539 Expander.clear(); 540 // If we generated new code for the base pointer, clean up. 541 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); 542 return false; 543 } 544 545 // Okay, everything looks good, insert the memset. 546 547 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 548 // pointer size if it isn't already. 549 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); 550 551 const SCEV *NumBytesS = 552 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW); 553 if (StoreSize != 1) { 554 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), 555 SCEV::FlagNUW); 556 } 557 558 Value *NumBytes = 559 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); 560 561 CallInst *NewCall; 562 if (SplatValue) { 563 NewCall = 564 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); 565 } else { 566 // Everything is emitted in default address space 567 Type *Int8PtrTy = DestInt8PtrTy; 568 569 Module *M = TheStore->getParent()->getParent()->getParent(); 570 Value *MSP = 571 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(), 572 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr); 573 574 // Otherwise we should form a memset_pattern16. PatternValue is known to be 575 // an constant array of 16-bytes. Plop the value into a mergable global. 576 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 577 GlobalValue::PrivateLinkage, 578 PatternValue, ".memset_pattern"); 579 GV->setUnnamedAddr(true); // Ok to merge these. 580 GV->setAlignment(16); 581 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 582 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 583 } 584 585 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 586 << " from store to: " << *Ev << " at: " << *TheStore << "\n"); 587 NewCall->setDebugLoc(TheStore->getDebugLoc()); 588 589 // Okay, the memset has been formed. Zap the original store and anything that 590 // feeds into it. 591 deleteDeadInstruction(TheStore, TLI); 592 ++NumMemSet; 593 return true; 594 } 595 596 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a 597 /// same-strided load. 598 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad( 599 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv, 600 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) { 601 // If we're not allowed to form memcpy, we fail. 602 if (!TLI->has(LibFunc::memcpy)) 603 return false; 604 605 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 606 607 // The trip count of the loop and the base pointer of the addrec SCEV is 608 // guaranteed to be loop invariant, which means that it should dominate the 609 // header. This allows us to insert code for it in the preheader. 610 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 611 IRBuilder<> Builder(Preheader->getTerminator()); 612 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 613 614 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 615 // this into a memcpy in the loop preheader now if we want. However, this 616 // would be unsafe to do if there is anything else in the loop that may read 617 // or write the memory region we're storing to. This includes the load that 618 // feeds the stores. Check for an alias by generating the base address and 619 // checking everything. 620 Value *StoreBasePtr = Expander.expandCodeFor( 621 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()), 622 Preheader->getTerminator()); 623 624 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount, 625 StoreSize, *AA, SI)) { 626 Expander.clear(); 627 // If we generated new code for the base pointer, clean up. 628 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 629 return false; 630 } 631 632 // For a memcpy, we have to make sure that the input array is not being 633 // mutated by the loop. 634 Value *LoadBasePtr = Expander.expandCodeFor( 635 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()), 636 Preheader->getTerminator()); 637 638 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize, 639 *AA, SI)) { 640 Expander.clear(); 641 // If we generated new code for the base pointer, clean up. 642 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); 643 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 644 return false; 645 } 646 647 // Okay, everything is safe, we can transform this! 648 649 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 650 // pointer size if it isn't already. 651 Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace()); 652 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); 653 654 const SCEV *NumBytesS = 655 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); 656 if (StoreSize != 1) 657 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), 658 SCEV::FlagNUW); 659 660 Value *NumBytes = 661 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); 662 663 CallInst *NewCall = 664 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, 665 std::min(SI->getAlignment(), LI->getAlignment())); 666 NewCall->setDebugLoc(SI->getDebugLoc()); 667 668 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" 669 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 670 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); 671 672 // Okay, the memcpy has been formed. Zap the original store and anything that 673 // feeds into it. 674 deleteDeadInstruction(SI, TLI); 675 ++NumMemCpy; 676 return true; 677 } 678 679 bool LoopIdiomRecognize::runOnNoncountableLoop() { 680 return recognizePopcount(); 681 } 682 683 /// Check if the given conditional branch is based on the comparison between 684 /// a variable and zero, and if the variable is non-zero, the control yields to 685 /// the loop entry. If the branch matches the behavior, the variable involved 686 /// in the comparion is returned. This function will be called to see if the 687 /// precondition and postcondition of the loop are in desirable form. 688 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) { 689 if (!BI || !BI->isConditional()) 690 return nullptr; 691 692 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 693 if (!Cond) 694 return nullptr; 695 696 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 697 if (!CmpZero || !CmpZero->isZero()) 698 return nullptr; 699 700 ICmpInst::Predicate Pred = Cond->getPredicate(); 701 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) || 702 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry)) 703 return Cond->getOperand(0); 704 705 return nullptr; 706 } 707 708 /// Return true iff the idiom is detected in the loop. 709 /// 710 /// Additionally: 711 /// 1) \p CntInst is set to the instruction counting the population bit. 712 /// 2) \p CntPhi is set to the corresponding phi node. 713 /// 3) \p Var is set to the value whose population bits are being counted. 714 /// 715 /// The core idiom we are trying to detect is: 716 /// \code 717 /// if (x0 != 0) 718 /// goto loop-exit // the precondition of the loop 719 /// cnt0 = init-val; 720 /// do { 721 /// x1 = phi (x0, x2); 722 /// cnt1 = phi(cnt0, cnt2); 723 /// 724 /// cnt2 = cnt1 + 1; 725 /// ... 726 /// x2 = x1 & (x1 - 1); 727 /// ... 728 /// } while(x != 0); 729 /// 730 /// loop-exit: 731 /// \endcode 732 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 733 Instruction *&CntInst, PHINode *&CntPhi, 734 Value *&Var) { 735 // step 1: Check to see if the look-back branch match this pattern: 736 // "if (a!=0) goto loop-entry". 737 BasicBlock *LoopEntry; 738 Instruction *DefX2, *CountInst; 739 Value *VarX1, *VarX0; 740 PHINode *PhiX, *CountPhi; 741 742 DefX2 = CountInst = nullptr; 743 VarX1 = VarX0 = nullptr; 744 PhiX = CountPhi = nullptr; 745 LoopEntry = *(CurLoop->block_begin()); 746 747 // step 1: Check if the loop-back branch is in desirable form. 748 { 749 if (Value *T = matchCondition( 750 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 751 DefX2 = dyn_cast<Instruction>(T); 752 else 753 return false; 754 } 755 756 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 757 { 758 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 759 return false; 760 761 BinaryOperator *SubOneOp; 762 763 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 764 VarX1 = DefX2->getOperand(1); 765 else { 766 VarX1 = DefX2->getOperand(0); 767 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 768 } 769 if (!SubOneOp) 770 return false; 771 772 Instruction *SubInst = cast<Instruction>(SubOneOp); 773 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); 774 if (!Dec || 775 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || 776 (SubInst->getOpcode() == Instruction::Add && 777 Dec->isAllOnesValue()))) { 778 return false; 779 } 780 } 781 782 // step 3: Check the recurrence of variable X 783 { 784 PhiX = dyn_cast<PHINode>(VarX1); 785 if (!PhiX || 786 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { 787 return false; 788 } 789 } 790 791 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 792 { 793 CountInst = nullptr; 794 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 795 IterE = LoopEntry->end(); 796 Iter != IterE; Iter++) { 797 Instruction *Inst = &*Iter; 798 if (Inst->getOpcode() != Instruction::Add) 799 continue; 800 801 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 802 if (!Inc || !Inc->isOne()) 803 continue; 804 805 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); 806 if (!Phi || Phi->getParent() != LoopEntry) 807 continue; 808 809 // Check if the result of the instruction is live of the loop. 810 bool LiveOutLoop = false; 811 for (User *U : Inst->users()) { 812 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 813 LiveOutLoop = true; 814 break; 815 } 816 } 817 818 if (LiveOutLoop) { 819 CountInst = Inst; 820 CountPhi = Phi; 821 break; 822 } 823 } 824 825 if (!CountInst) 826 return false; 827 } 828 829 // step 5: check if the precondition is in this form: 830 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 831 { 832 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 833 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 834 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 835 return false; 836 837 CntInst = CountInst; 838 CntPhi = CountPhi; 839 Var = T; 840 } 841 842 return true; 843 } 844 845 /// Recognizes a population count idiom in a non-countable loop. 846 /// 847 /// If detected, transforms the relevant code to issue the popcount intrinsic 848 /// function call, and returns true; otherwise, returns false. 849 bool LoopIdiomRecognize::recognizePopcount() { 850 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 851 return false; 852 853 // Counting population are usually conducted by few arithmetic instructions. 854 // Such instructions can be easily "absorbed" by vacant slots in a 855 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 856 // in a compact loop. 857 858 // Give up if the loop has multiple blocks or multiple backedges. 859 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 860 return false; 861 862 BasicBlock *LoopBody = *(CurLoop->block_begin()); 863 if (LoopBody->size() >= 20) { 864 // The loop is too big, bail out. 865 return false; 866 } 867 868 // It should have a preheader containing nothing but an unconditional branch. 869 BasicBlock *PH = CurLoop->getLoopPreheader(); 870 if (!PH) 871 return false; 872 if (&PH->front() != PH->getTerminator()) 873 return false; 874 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 875 if (!EntryBI || EntryBI->isConditional()) 876 return false; 877 878 // It should have a precondition block where the generated popcount instrinsic 879 // function can be inserted. 880 auto *PreCondBB = PH->getSinglePredecessor(); 881 if (!PreCondBB) 882 return false; 883 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 884 if (!PreCondBI || PreCondBI->isUnconditional()) 885 return false; 886 887 Instruction *CntInst; 888 PHINode *CntPhi; 889 Value *Val; 890 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 891 return false; 892 893 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 894 return true; 895 } 896 897 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 898 DebugLoc DL) { 899 Value *Ops[] = {Val}; 900 Type *Tys[] = {Val->getType()}; 901 902 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 903 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 904 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 905 CI->setDebugLoc(DL); 906 907 return CI; 908 } 909 910 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 911 Instruction *CntInst, 912 PHINode *CntPhi, Value *Var) { 913 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 914 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 915 const DebugLoc DL = CntInst->getDebugLoc(); 916 917 // Assuming before transformation, the loop is following: 918 // if (x) // the precondition 919 // do { cnt++; x &= x - 1; } while(x); 920 921 // Step 1: Insert the ctpop instruction at the end of the precondition block 922 IRBuilder<> Builder(PreCondBr); 923 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 924 { 925 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 926 NewCount = PopCntZext = 927 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 928 929 if (NewCount != PopCnt) 930 (cast<Instruction>(NewCount))->setDebugLoc(DL); 931 932 // TripCnt is exactly the number of iterations the loop has 933 TripCnt = NewCount; 934 935 // If the population counter's initial value is not zero, insert Add Inst. 936 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 937 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 938 if (!InitConst || !InitConst->isZero()) { 939 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 940 (cast<Instruction>(NewCount))->setDebugLoc(DL); 941 } 942 } 943 944 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 945 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 946 // function would be partial dead code, and downstream passes will drag 947 // it back from the precondition block to the preheader. 948 { 949 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 950 951 Value *Opnd0 = PopCntZext; 952 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 953 if (PreCond->getOperand(0) != Var) 954 std::swap(Opnd0, Opnd1); 955 956 ICmpInst *NewPreCond = cast<ICmpInst>( 957 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 958 PreCondBr->setCondition(NewPreCond); 959 960 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 961 } 962 963 // Step 3: Note that the population count is exactly the trip count of the 964 // loop in question, which enable us to to convert the loop from noncountable 965 // loop into a countable one. The benefit is twofold: 966 // 967 // - If the loop only counts population, the entire loop becomes dead after 968 // the transformation. It is a lot easier to prove a countable loop dead 969 // than to prove a noncountable one. (In some C dialects, an infinite loop 970 // isn't dead even if it computes nothing useful. In general, DCE needs 971 // to prove a noncountable loop finite before safely delete it.) 972 // 973 // - If the loop also performs something else, it remains alive. 974 // Since it is transformed to countable form, it can be aggressively 975 // optimized by some optimizations which are in general not applicable 976 // to a noncountable loop. 977 // 978 // After this step, this loop (conceptually) would look like following: 979 // newcnt = __builtin_ctpop(x); 980 // t = newcnt; 981 // if (x) 982 // do { cnt++; x &= x-1; t--) } while (t > 0); 983 BasicBlock *Body = *(CurLoop->block_begin()); 984 { 985 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); 986 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 987 Type *Ty = TripCnt->getType(); 988 989 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 990 991 Builder.SetInsertPoint(LbCond); 992 Instruction *TcDec = cast<Instruction>( 993 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 994 "tcdec", false, true)); 995 996 TcPhi->addIncoming(TripCnt, PreHead); 997 TcPhi->addIncoming(TcDec, Body); 998 999 CmpInst::Predicate Pred = 1000 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 1001 LbCond->setPredicate(Pred); 1002 LbCond->setOperand(0, TcDec); 1003 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1004 } 1005 1006 // Step 4: All the references to the original population counter outside 1007 // the loop are replaced with the NewCount -- the value returned from 1008 // __builtin_ctpop(). 1009 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1010 1011 // step 5: Forget the "non-computable" trip-count SCEV associated with the 1012 // loop. The loop would otherwise not be deleted even if it becomes empty. 1013 SE->forgetLoop(CurLoop); 1014 } 1015