1 //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass implements an idiom recognizer that transforms simple loops into a 10 // non-loop form. In cases that this kicks in, it can be a significant 11 // performance win. 12 // 13 // If compiling for code size we avoid idiom recognition if the resulting 14 // code could be larger than the code for the original loop. One way this could 15 // happen is if the loop is not removable after idiom recognition due to the 16 // presence of non-idiom instructions. The initial implementation of the 17 // heuristics applies to idioms in multi-block loops. 18 // 19 //===----------------------------------------------------------------------===// 20 // 21 // TODO List: 22 // 23 // Future loop memory idioms to recognize: 24 // memcmp, memmove, strlen, etc. 25 // Future floating point idioms to recognize in -ffast-math mode: 26 // fpowi 27 // Future integer operation idioms to recognize: 28 // ctpop 29 // 30 // Beware that isel's default lowering for ctpop is highly inefficient for 31 // i64 and larger types when i64 is legal and the value has few bits set. It 32 // would be good to enhance isel to emit a loop for ctpop in this case. 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/LoopIdiomRecognize.h" 40 #include "llvm/ADT/APInt.h" 41 #include "llvm/ADT/ArrayRef.h" 42 #include "llvm/ADT/DenseMap.h" 43 #include "llvm/ADT/MapVector.h" 44 #include "llvm/ADT/SetVector.h" 45 #include "llvm/ADT/SmallPtrSet.h" 46 #include "llvm/ADT/SmallVector.h" 47 #include "llvm/ADT/Statistic.h" 48 #include "llvm/ADT/StringRef.h" 49 #include "llvm/Analysis/AliasAnalysis.h" 50 #include "llvm/Analysis/LoopAccessAnalysis.h" 51 #include "llvm/Analysis/LoopInfo.h" 52 #include "llvm/Analysis/LoopPass.h" 53 #include "llvm/Analysis/MemoryLocation.h" 54 #include "llvm/Analysis/MemorySSA.h" 55 #include "llvm/Analysis/MemorySSAUpdater.h" 56 #include "llvm/Analysis/MustExecute.h" 57 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 58 #include "llvm/Analysis/ScalarEvolution.h" 59 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 60 #include "llvm/Analysis/TargetLibraryInfo.h" 61 #include "llvm/Analysis/TargetTransformInfo.h" 62 #include "llvm/Analysis/ValueTracking.h" 63 #include "llvm/IR/Attributes.h" 64 #include "llvm/IR/BasicBlock.h" 65 #include "llvm/IR/Constant.h" 66 #include "llvm/IR/Constants.h" 67 #include "llvm/IR/DataLayout.h" 68 #include "llvm/IR/DebugLoc.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/Dominators.h" 71 #include "llvm/IR/GlobalValue.h" 72 #include "llvm/IR/GlobalVariable.h" 73 #include "llvm/IR/IRBuilder.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instruction.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Module.h" 81 #include "llvm/IR/PassManager.h" 82 #include "llvm/IR/Type.h" 83 #include "llvm/IR/User.h" 84 #include "llvm/IR/Value.h" 85 #include "llvm/IR/ValueHandle.h" 86 #include "llvm/InitializePasses.h" 87 #include "llvm/Pass.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Transforms/Scalar.h" 93 #include "llvm/Transforms/Utils/BuildLibCalls.h" 94 #include "llvm/Transforms/Utils/Local.h" 95 #include "llvm/Transforms/Utils/LoopUtils.h" 96 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 97 #include <algorithm> 98 #include <cassert> 99 #include <cstdint> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 105 #define DEBUG_TYPE "loop-idiom" 106 107 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 108 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 109 110 static cl::opt<bool> UseLIRCodeSizeHeurs( 111 "use-lir-code-size-heurs", 112 cl::desc("Use loop idiom recognition code size heuristics when compiling" 113 "with -Os/-Oz"), 114 cl::init(true), cl::Hidden); 115 116 namespace { 117 118 class LoopIdiomRecognize { 119 Loop *CurLoop = nullptr; 120 AliasAnalysis *AA; 121 DominatorTree *DT; 122 LoopInfo *LI; 123 ScalarEvolution *SE; 124 TargetLibraryInfo *TLI; 125 const TargetTransformInfo *TTI; 126 const DataLayout *DL; 127 OptimizationRemarkEmitter &ORE; 128 bool ApplyCodeSizeHeuristics; 129 std::unique_ptr<MemorySSAUpdater> MSSAU; 130 131 public: 132 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 133 LoopInfo *LI, ScalarEvolution *SE, 134 TargetLibraryInfo *TLI, 135 const TargetTransformInfo *TTI, MemorySSA *MSSA, 136 const DataLayout *DL, 137 OptimizationRemarkEmitter &ORE) 138 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) { 139 if (MSSA) 140 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 141 } 142 143 bool runOnLoop(Loop *L); 144 145 private: 146 using StoreList = SmallVector<StoreInst *, 8>; 147 using StoreListMap = MapVector<Value *, StoreList>; 148 149 StoreListMap StoreRefsForMemset; 150 StoreListMap StoreRefsForMemsetPattern; 151 StoreList StoreRefsForMemcpy; 152 bool HasMemset; 153 bool HasMemsetPattern; 154 bool HasMemcpy; 155 156 /// Return code for isLegalStore() 157 enum LegalStoreKind { 158 None = 0, 159 Memset, 160 MemsetPattern, 161 Memcpy, 162 UnorderedAtomicMemcpy, 163 DontUse // Dummy retval never to be used. Allows catching errors in retval 164 // handling. 165 }; 166 167 /// \name Countable Loop Idiom Handling 168 /// @{ 169 170 bool runOnCountableLoop(); 171 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 172 SmallVectorImpl<BasicBlock *> &ExitBlocks); 173 174 void collectStores(BasicBlock *BB); 175 LegalStoreKind isLegalStore(StoreInst *SI); 176 enum class ForMemset { No, Yes }; 177 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, 178 ForMemset For); 179 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 180 181 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, 182 MaybeAlign StoreAlignment, Value *StoredVal, 183 Instruction *TheStore, 184 SmallPtrSetImpl<Instruction *> &Stores, 185 const SCEVAddRecExpr *Ev, const SCEV *BECount, 186 bool NegStride, bool IsLoopMemset = false); 187 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); 188 bool avoidLIRForMultiBlockLoop(bool IsMemset = false, 189 bool IsLoopMemset = false); 190 191 /// @} 192 /// \name Noncountable Loop Idiom Handling 193 /// @{ 194 195 bool runOnNoncountableLoop(); 196 197 bool recognizePopcount(); 198 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 199 PHINode *CntPhi, Value *Var); 200 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz 201 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB, 202 Instruction *CntInst, PHINode *CntPhi, 203 Value *Var, Instruction *DefX, 204 const DebugLoc &DL, bool ZeroCheck, 205 bool IsCntPhiUsedOutsideLoop); 206 207 /// @} 208 }; 209 210 class LoopIdiomRecognizeLegacyPass : public LoopPass { 211 public: 212 static char ID; 213 214 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 215 initializeLoopIdiomRecognizeLegacyPassPass( 216 *PassRegistry::getPassRegistry()); 217 } 218 219 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 220 if (skipLoop(L)) 221 return false; 222 223 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 224 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 225 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 226 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 227 TargetLibraryInfo *TLI = 228 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 229 *L->getHeader()->getParent()); 230 const TargetTransformInfo *TTI = 231 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 232 *L->getHeader()->getParent()); 233 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); 234 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 235 MemorySSA *MSSA = nullptr; 236 if (MSSAAnalysis) 237 MSSA = &MSSAAnalysis->getMSSA(); 238 239 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 240 // pass. Function analyses need to be preserved across loop transformations 241 // but ORE cannot be preserved (see comment before the pass definition). 242 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 243 244 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE); 245 return LIR.runOnLoop(L); 246 } 247 248 /// This transformation requires natural loop information & requires that 249 /// loop preheaders be inserted into the CFG. 250 void getAnalysisUsage(AnalysisUsage &AU) const override { 251 AU.addRequired<TargetLibraryInfoWrapperPass>(); 252 AU.addRequired<TargetTransformInfoWrapperPass>(); 253 AU.addPreserved<MemorySSAWrapperPass>(); 254 getLoopAnalysisUsage(AU); 255 } 256 }; 257 258 } // end anonymous namespace 259 260 char LoopIdiomRecognizeLegacyPass::ID = 0; 261 262 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, 263 LoopStandardAnalysisResults &AR, 264 LPMUpdater &) { 265 const auto *DL = &L.getHeader()->getModule()->getDataLayout(); 266 267 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis 268 // pass. Function analyses need to be preserved across loop transformations 269 // but ORE cannot be preserved (see comment before the pass definition). 270 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 271 272 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, 273 AR.MSSA, DL, ORE); 274 if (!LIR.runOnLoop(&L)) 275 return PreservedAnalyses::all(); 276 277 auto PA = getLoopPassPreservedAnalyses(); 278 if (AR.MSSA) 279 PA.preserve<MemorySSAAnalysis>(); 280 return PA; 281 } 282 283 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", 284 "Recognize loop idioms", false, false) 285 INITIALIZE_PASS_DEPENDENCY(LoopPass) 286 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 287 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 288 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", 289 "Recognize loop idioms", false, false) 290 291 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } 292 293 static void deleteDeadInstruction(Instruction *I) { 294 I->replaceAllUsesWith(UndefValue::get(I->getType())); 295 I->eraseFromParent(); 296 } 297 298 namespace { 299 class ExpandedValuesCleaner { 300 SCEVExpander &Expander; 301 TargetLibraryInfo *TLI; 302 SmallVector<Value *, 4> ExpandedValues; 303 bool Commit = false; 304 305 public: 306 ExpandedValuesCleaner(SCEVExpander &Expander, TargetLibraryInfo *TLI) 307 : Expander(Expander), TLI(TLI) {} 308 309 void add(Value *V) { ExpandedValues.push_back(V); } 310 311 void commit() { Commit = true; } 312 313 ~ExpandedValuesCleaner() { 314 if (!Commit) { 315 Expander.clear(); 316 for (auto *V : ExpandedValues) 317 RecursivelyDeleteTriviallyDeadInstructions(V, TLI); 318 } 319 } 320 }; 321 } // namespace 322 323 //===----------------------------------------------------------------------===// 324 // 325 // Implementation of LoopIdiomRecognize 326 // 327 //===----------------------------------------------------------------------===// 328 329 bool LoopIdiomRecognize::runOnLoop(Loop *L) { 330 CurLoop = L; 331 // If the loop could not be converted to canonical form, it must have an 332 // indirectbr in it, just give up. 333 if (!L->getLoopPreheader()) 334 return false; 335 336 // Disable loop idiom recognition if the function's name is a common idiom. 337 StringRef Name = L->getHeader()->getParent()->getName(); 338 if (Name == "memset" || Name == "memcpy") 339 return false; 340 341 // Determine if code size heuristics need to be applied. 342 ApplyCodeSizeHeuristics = 343 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs; 344 345 HasMemset = TLI->has(LibFunc_memset); 346 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); 347 HasMemcpy = TLI->has(LibFunc_memcpy); 348 349 if (HasMemset || HasMemsetPattern || HasMemcpy) 350 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 351 return runOnCountableLoop(); 352 353 return runOnNoncountableLoop(); 354 } 355 356 bool LoopIdiomRecognize::runOnCountableLoop() { 357 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 358 assert(!isa<SCEVCouldNotCompute>(BECount) && 359 "runOnCountableLoop() called on a loop without a predictable" 360 "backedge-taken count"); 361 362 // If this loop executes exactly one time, then it should be peeled, not 363 // optimized by this pass. 364 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 365 if (BECst->getAPInt() == 0) 366 return false; 367 368 SmallVector<BasicBlock *, 8> ExitBlocks; 369 CurLoop->getUniqueExitBlocks(ExitBlocks); 370 371 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 372 << CurLoop->getHeader()->getParent()->getName() 373 << "] Countable Loop %" << CurLoop->getHeader()->getName() 374 << "\n"); 375 376 // The following transforms hoist stores/memsets into the loop pre-header. 377 // Give up if the loop has instructions that may throw. 378 SimpleLoopSafetyInfo SafetyInfo; 379 SafetyInfo.computeLoopSafetyInfo(CurLoop); 380 if (SafetyInfo.anyBlockMayThrow()) 381 return false; 382 383 bool MadeChange = false; 384 385 // Scan all the blocks in the loop that are not in subloops. 386 for (auto *BB : CurLoop->getBlocks()) { 387 // Ignore blocks in subloops. 388 if (LI->getLoopFor(BB) != CurLoop) 389 continue; 390 391 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 392 } 393 return MadeChange; 394 } 395 396 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { 397 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 398 return ConstStride->getAPInt(); 399 } 400 401 /// getMemSetPatternValue - If a strided store of the specified value is safe to 402 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 403 /// be passed in. Otherwise, return null. 404 /// 405 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 406 /// just replicate their input array and then pass on to memset_pattern16. 407 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 408 // FIXME: This could check for UndefValue because it can be merged into any 409 // other valid pattern. 410 411 // If the value isn't a constant, we can't promote it to being in a constant 412 // array. We could theoretically do a store to an alloca or something, but 413 // that doesn't seem worthwhile. 414 Constant *C = dyn_cast<Constant>(V); 415 if (!C) 416 return nullptr; 417 418 // Only handle simple values that are a power of two bytes in size. 419 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 420 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 421 return nullptr; 422 423 // Don't care enough about darwin/ppc to implement this. 424 if (DL->isBigEndian()) 425 return nullptr; 426 427 // Convert to size in bytes. 428 Size /= 8; 429 430 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 431 // if the top and bottom are the same (e.g. for vectors and large integers). 432 if (Size > 16) 433 return nullptr; 434 435 // If the constant is exactly 16 bytes, just use it. 436 if (Size == 16) 437 return C; 438 439 // Otherwise, we'll use an array of the constants. 440 unsigned ArraySize = 16 / Size; 441 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 442 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 443 } 444 445 LoopIdiomRecognize::LegalStoreKind 446 LoopIdiomRecognize::isLegalStore(StoreInst *SI) { 447 // Don't touch volatile stores. 448 if (SI->isVolatile()) 449 return LegalStoreKind::None; 450 // We only want simple or unordered-atomic stores. 451 if (!SI->isUnordered()) 452 return LegalStoreKind::None; 453 454 // Don't convert stores of non-integral pointer types to memsets (which stores 455 // integers). 456 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType())) 457 return LegalStoreKind::None; 458 459 // Avoid merging nontemporal stores. 460 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 461 return LegalStoreKind::None; 462 463 Value *StoredVal = SI->getValueOperand(); 464 Value *StorePtr = SI->getPointerOperand(); 465 466 // Reject stores that are so large that they overflow an unsigned. 467 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 468 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) 469 return LegalStoreKind::None; 470 471 // See if the pointer expression is an AddRec like {base,+,1} on the current 472 // loop, which indicates a strided store. If we have something else, it's a 473 // random store we can't handle. 474 const SCEVAddRecExpr *StoreEv = 475 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 476 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 477 return LegalStoreKind::None; 478 479 // Check to see if we have a constant stride. 480 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 481 return LegalStoreKind::None; 482 483 // See if the store can be turned into a memset. 484 485 // If the stored value is a byte-wise value (like i32 -1), then it may be 486 // turned into a memset of i8 -1, assuming that all the consecutive bytes 487 // are stored. A store of i32 0x01020304 can never be turned into a memset, 488 // but it can be turned into memset_pattern if the target supports it. 489 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 490 Constant *PatternValue = nullptr; 491 492 // Note: memset and memset_pattern on unordered-atomic is yet not supported 493 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple(); 494 495 // If we're allowed to form a memset, and the stored value would be 496 // acceptable for memset, use it. 497 if (!UnorderedAtomic && HasMemset && SplatValue && 498 // Verify that the stored value is loop invariant. If not, we can't 499 // promote the memset. 500 CurLoop->isLoopInvariant(SplatValue)) { 501 // It looks like we can use SplatValue. 502 return LegalStoreKind::Memset; 503 } else if (!UnorderedAtomic && HasMemsetPattern && 504 // Don't create memset_pattern16s with address spaces. 505 StorePtr->getType()->getPointerAddressSpace() == 0 && 506 (PatternValue = getMemSetPatternValue(StoredVal, DL))) { 507 // It looks like we can use PatternValue! 508 return LegalStoreKind::MemsetPattern; 509 } 510 511 // Otherwise, see if the store can be turned into a memcpy. 512 if (HasMemcpy) { 513 // Check to see if the stride matches the size of the store. If so, then we 514 // know that every byte is touched in the loop. 515 APInt Stride = getStoreStride(StoreEv); 516 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 517 if (StoreSize != Stride && StoreSize != -Stride) 518 return LegalStoreKind::None; 519 520 // The store must be feeding a non-volatile load. 521 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 522 523 // Only allow non-volatile loads 524 if (!LI || LI->isVolatile()) 525 return LegalStoreKind::None; 526 // Only allow simple or unordered-atomic loads 527 if (!LI->isUnordered()) 528 return LegalStoreKind::None; 529 530 // See if the pointer expression is an AddRec like {base,+,1} on the current 531 // loop, which indicates a strided load. If we have something else, it's a 532 // random load we can't handle. 533 const SCEVAddRecExpr *LoadEv = 534 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 535 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 536 return LegalStoreKind::None; 537 538 // The store and load must share the same stride. 539 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 540 return LegalStoreKind::None; 541 542 // Success. This store can be converted into a memcpy. 543 UnorderedAtomic = UnorderedAtomic || LI->isAtomic(); 544 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy 545 : LegalStoreKind::Memcpy; 546 } 547 // This store can't be transformed into a memset/memcpy. 548 return LegalStoreKind::None; 549 } 550 551 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 552 StoreRefsForMemset.clear(); 553 StoreRefsForMemsetPattern.clear(); 554 StoreRefsForMemcpy.clear(); 555 for (Instruction &I : *BB) { 556 StoreInst *SI = dyn_cast<StoreInst>(&I); 557 if (!SI) 558 continue; 559 560 // Make sure this is a strided store with a constant stride. 561 switch (isLegalStore(SI)) { 562 case LegalStoreKind::None: 563 // Nothing to do 564 break; 565 case LegalStoreKind::Memset: { 566 // Find the base pointer. 567 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 568 StoreRefsForMemset[Ptr].push_back(SI); 569 } break; 570 case LegalStoreKind::MemsetPattern: { 571 // Find the base pointer. 572 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); 573 StoreRefsForMemsetPattern[Ptr].push_back(SI); 574 } break; 575 case LegalStoreKind::Memcpy: 576 case LegalStoreKind::UnorderedAtomicMemcpy: 577 StoreRefsForMemcpy.push_back(SI); 578 break; 579 default: 580 assert(false && "unhandled return value"); 581 break; 582 } 583 } 584 } 585 586 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 587 /// with the specified backedge count. This block is known to be in the current 588 /// loop and not in any subloops. 589 bool LoopIdiomRecognize::runOnLoopBlock( 590 BasicBlock *BB, const SCEV *BECount, 591 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 592 // We can only promote stores in this block if they are unconditionally 593 // executed in the loop. For a block to be unconditionally executed, it has 594 // to dominate all the exit blocks of the loop. Verify this now. 595 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 596 if (!DT->dominates(BB, ExitBlocks[i])) 597 return false; 598 599 bool MadeChange = false; 600 // Look for store instructions, which may be optimized to memset/memcpy. 601 collectStores(BB); 602 603 // Look for a single store or sets of stores with a common base, which can be 604 // optimized into a memset (memset_pattern). The latter most commonly happens 605 // with structs and handunrolled loops. 606 for (auto &SL : StoreRefsForMemset) 607 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes); 608 609 for (auto &SL : StoreRefsForMemsetPattern) 610 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No); 611 612 // Optimize the store into a memcpy, if it feeds an similarly strided load. 613 for (auto &SI : StoreRefsForMemcpy) 614 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 615 616 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 617 Instruction *Inst = &*I++; 618 // Look for memset instructions, which may be optimized to a larger memset. 619 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { 620 WeakTrackingVH InstPtr(&*I); 621 if (!processLoopMemSet(MSI, BECount)) 622 continue; 623 MadeChange = true; 624 625 // If processing the memset invalidated our iterator, start over from the 626 // top of the block. 627 if (!InstPtr) 628 I = BB->begin(); 629 continue; 630 } 631 } 632 633 return MadeChange; 634 } 635 636 /// See if this store(s) can be promoted to a memset. 637 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, 638 const SCEV *BECount, ForMemset For) { 639 // Try to find consecutive stores that can be transformed into memsets. 640 SetVector<StoreInst *> Heads, Tails; 641 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 642 643 // Do a quadratic search on all of the given stores and find 644 // all of the pairs of stores that follow each other. 645 SmallVector<unsigned, 16> IndexQueue; 646 for (unsigned i = 0, e = SL.size(); i < e; ++i) { 647 assert(SL[i]->isSimple() && "Expected only non-volatile stores."); 648 649 Value *FirstStoredVal = SL[i]->getValueOperand(); 650 Value *FirstStorePtr = SL[i]->getPointerOperand(); 651 const SCEVAddRecExpr *FirstStoreEv = 652 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); 653 APInt FirstStride = getStoreStride(FirstStoreEv); 654 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType()); 655 656 // See if we can optimize just this store in isolation. 657 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { 658 Heads.insert(SL[i]); 659 continue; 660 } 661 662 Value *FirstSplatValue = nullptr; 663 Constant *FirstPatternValue = nullptr; 664 665 if (For == ForMemset::Yes) 666 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL); 667 else 668 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); 669 670 assert((FirstSplatValue || FirstPatternValue) && 671 "Expected either splat value or pattern value."); 672 673 IndexQueue.clear(); 674 // If a store has multiple consecutive store candidates, search Stores 675 // array according to the sequence: from i+1 to e, then from i-1 to 0. 676 // This is because usually pairing with immediate succeeding or preceding 677 // candidate create the best chance to find memset opportunity. 678 unsigned j = 0; 679 for (j = i + 1; j < e; ++j) 680 IndexQueue.push_back(j); 681 for (j = i; j > 0; --j) 682 IndexQueue.push_back(j - 1); 683 684 for (auto &k : IndexQueue) { 685 assert(SL[k]->isSimple() && "Expected only non-volatile stores."); 686 Value *SecondStorePtr = SL[k]->getPointerOperand(); 687 const SCEVAddRecExpr *SecondStoreEv = 688 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); 689 APInt SecondStride = getStoreStride(SecondStoreEv); 690 691 if (FirstStride != SecondStride) 692 continue; 693 694 Value *SecondStoredVal = SL[k]->getValueOperand(); 695 Value *SecondSplatValue = nullptr; 696 Constant *SecondPatternValue = nullptr; 697 698 if (For == ForMemset::Yes) 699 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL); 700 else 701 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); 702 703 assert((SecondSplatValue || SecondPatternValue) && 704 "Expected either splat value or pattern value."); 705 706 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { 707 if (For == ForMemset::Yes) { 708 if (isa<UndefValue>(FirstSplatValue)) 709 FirstSplatValue = SecondSplatValue; 710 if (FirstSplatValue != SecondSplatValue) 711 continue; 712 } else { 713 if (isa<UndefValue>(FirstPatternValue)) 714 FirstPatternValue = SecondPatternValue; 715 if (FirstPatternValue != SecondPatternValue) 716 continue; 717 } 718 Tails.insert(SL[k]); 719 Heads.insert(SL[i]); 720 ConsecutiveChain[SL[i]] = SL[k]; 721 break; 722 } 723 } 724 } 725 726 // We may run into multiple chains that merge into a single chain. We mark the 727 // stores that we transformed so that we don't visit the same store twice. 728 SmallPtrSet<Value *, 16> TransformedStores; 729 bool Changed = false; 730 731 // For stores that start but don't end a link in the chain: 732 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 733 it != e; ++it) { 734 if (Tails.count(*it)) 735 continue; 736 737 // We found a store instr that starts a chain. Now follow the chain and try 738 // to transform it. 739 SmallPtrSet<Instruction *, 8> AdjacentStores; 740 StoreInst *I = *it; 741 742 StoreInst *HeadStore = I; 743 unsigned StoreSize = 0; 744 745 // Collect the chain into a list. 746 while (Tails.count(I) || Heads.count(I)) { 747 if (TransformedStores.count(I)) 748 break; 749 AdjacentStores.insert(I); 750 751 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType()); 752 // Move to the next value in the chain. 753 I = ConsecutiveChain[I]; 754 } 755 756 Value *StoredVal = HeadStore->getValueOperand(); 757 Value *StorePtr = HeadStore->getPointerOperand(); 758 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 759 APInt Stride = getStoreStride(StoreEv); 760 761 // Check to see if the stride matches the size of the stores. If so, then 762 // we know that every byte is touched in the loop. 763 if (StoreSize != Stride && StoreSize != -Stride) 764 continue; 765 766 bool NegStride = StoreSize == -Stride; 767 768 if (processLoopStridedStore(StorePtr, StoreSize, 769 MaybeAlign(HeadStore->getAlignment()), 770 StoredVal, HeadStore, AdjacentStores, StoreEv, 771 BECount, NegStride)) { 772 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); 773 Changed = true; 774 } 775 } 776 777 return Changed; 778 } 779 780 /// processLoopMemSet - See if this memset can be promoted to a large memset. 781 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 782 const SCEV *BECount) { 783 // We can only handle non-volatile memsets with a constant size. 784 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) 785 return false; 786 787 // If we're not allowed to hack on memset, we fail. 788 if (!HasMemset) 789 return false; 790 791 Value *Pointer = MSI->getDest(); 792 793 // See if the pointer expression is an AddRec like {base,+,1} on the current 794 // loop, which indicates a strided store. If we have something else, it's a 795 // random store we can't handle. 796 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 797 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) 798 return false; 799 800 // Reject memsets that are so large that they overflow an unsigned. 801 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 802 if ((SizeInBytes >> 32) != 0) 803 return false; 804 805 // Check to see if the stride matches the size of the memset. If so, then we 806 // know that every byte is touched in the loop. 807 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 808 if (!ConstStride) 809 return false; 810 811 APInt Stride = ConstStride->getAPInt(); 812 if (SizeInBytes != Stride && SizeInBytes != -Stride) 813 return false; 814 815 // Verify that the memset value is loop invariant. If not, we can't promote 816 // the memset. 817 Value *SplatValue = MSI->getValue(); 818 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 819 return false; 820 821 SmallPtrSet<Instruction *, 1> MSIs; 822 MSIs.insert(MSI); 823 bool NegStride = SizeInBytes == -Stride; 824 return processLoopStridedStore( 825 Pointer, (unsigned)SizeInBytes, MaybeAlign(MSI->getDestAlignment()), 826 SplatValue, MSI, MSIs, Ev, BECount, NegStride, /*IsLoopMemset=*/true); 827 } 828 829 /// mayLoopAccessLocation - Return true if the specified loop might access the 830 /// specified pointer location, which is a loop-strided access. The 'Access' 831 /// argument specifies what the verboten forms of access are (read or write). 832 static bool 833 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 834 const SCEV *BECount, unsigned StoreSize, 835 AliasAnalysis &AA, 836 SmallPtrSetImpl<Instruction *> &IgnoredStores) { 837 // Get the location that may be stored across the loop. Since the access is 838 // strided positively through memory, we say that the modified location starts 839 // at the pointer and has infinite size. 840 LocationSize AccessSize = LocationSize::unknown(); 841 842 // If the loop iterates a fixed number of times, we can refine the access size 843 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 844 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 845 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * 846 StoreSize); 847 848 // TODO: For this to be really effective, we have to dive into the pointer 849 // operand in the store. Store to &A[i] of 100 will always return may alias 850 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 851 // which will then no-alias a store to &A[100]. 852 MemoryLocation StoreLoc(Ptr, AccessSize); 853 854 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 855 ++BI) 856 for (Instruction &I : **BI) 857 if (IgnoredStores.count(&I) == 0 && 858 isModOrRefSet( 859 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access))) 860 return true; 861 862 return false; 863 } 864 865 // If we have a negative stride, Start refers to the end of the memory location 866 // we're trying to memset. Therefore, we need to recompute the base pointer, 867 // which is just Start - BECount*Size. 868 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, 869 Type *IntPtr, unsigned StoreSize, 870 ScalarEvolution *SE) { 871 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 872 if (StoreSize != 1) 873 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), 874 SCEV::FlagNUW); 875 return SE->getMinusSCEV(Start, Index); 876 } 877 878 /// Compute the number of bytes as a SCEV from the backedge taken count. 879 /// 880 /// This also maps the SCEV into the provided type and tries to handle the 881 /// computation in a way that will fold cleanly. 882 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr, 883 unsigned StoreSize, Loop *CurLoop, 884 const DataLayout *DL, ScalarEvolution *SE) { 885 const SCEV *NumBytesS; 886 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 887 // pointer size if it isn't already. 888 // 889 // If we're going to need to zero extend the BE count, check if we can add 890 // one to it prior to zero extending without overflow. Provided this is safe, 891 // it allows better simplification of the +1. 892 if (DL->getTypeSizeInBits(BECount->getType()) < 893 DL->getTypeSizeInBits(IntPtr) && 894 SE->isLoopEntryGuardedByCond( 895 CurLoop, ICmpInst::ICMP_NE, BECount, 896 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) { 897 NumBytesS = SE->getZeroExtendExpr( 898 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW), 899 IntPtr); 900 } else { 901 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr), 902 SE->getOne(IntPtr), SCEV::FlagNUW); 903 } 904 905 // And scale it based on the store size. 906 if (StoreSize != 1) { 907 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), 908 SCEV::FlagNUW); 909 } 910 return NumBytesS; 911 } 912 913 /// processLoopStridedStore - We see a strided store of some value. If we can 914 /// transform this into a memset or memset_pattern in the loop preheader, do so. 915 bool LoopIdiomRecognize::processLoopStridedStore( 916 Value *DestPtr, unsigned StoreSize, MaybeAlign StoreAlignment, 917 Value *StoredVal, Instruction *TheStore, 918 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, 919 const SCEV *BECount, bool NegStride, bool IsLoopMemset) { 920 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 921 Constant *PatternValue = nullptr; 922 923 if (!SplatValue) 924 PatternValue = getMemSetPatternValue(StoredVal, DL); 925 926 assert((SplatValue || PatternValue) && 927 "Expected either splat value or pattern value."); 928 929 // The trip count of the loop and the base pointer of the addrec SCEV is 930 // guaranteed to be loop invariant, which means that it should dominate the 931 // header. This allows us to insert code for it in the preheader. 932 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 933 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 934 IRBuilder<> Builder(Preheader->getTerminator()); 935 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 936 ExpandedValuesCleaner EVC(Expander, TLI); 937 938 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 939 Type *IntIdxTy = DL->getIndexType(DestPtr->getType()); 940 941 bool Changed = false; 942 const SCEV *Start = Ev->getStart(); 943 // Handle negative strided loops. 944 if (NegStride) 945 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSize, SE); 946 947 // TODO: ideally we should still be able to generate memset if SCEV expander 948 // is taught to generate the dependencies at the latest point. 949 if (!isSafeToExpand(Start, *SE)) 950 return Changed; 951 952 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 953 // this into a memset in the loop preheader now if we want. However, this 954 // would be unsafe to do if there is anything else in the loop that may read 955 // or write to the aliased location. Check for any overlap by generating the 956 // base pointer and checking the region. 957 Value *BasePtr = 958 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 959 EVC.add(BasePtr); 960 961 // From here on out, conservatively report to the pass manager that we've 962 // changed the IR, even if we later clean up these added instructions. There 963 // may be structural differences e.g. in the order of use lists not accounted 964 // for in just a textual dump of the IR. This is written as a variable, even 965 // though statically all the places this dominates could be replaced with 966 // 'true', with the hope that anyone trying to be clever / "more precise" with 967 // the return value will read this comment, and leave them alone. 968 Changed = true; 969 970 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount, 971 StoreSize, *AA, Stores)) 972 return Changed; 973 974 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) 975 return Changed; 976 977 // Okay, everything looks good, insert the memset. 978 979 const SCEV *NumBytesS = 980 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE); 981 982 // TODO: ideally we should still be able to generate memset if SCEV expander 983 // is taught to generate the dependencies at the latest point. 984 if (!isSafeToExpand(NumBytesS, *SE)) 985 return Changed; 986 987 Value *NumBytes = 988 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 989 990 CallInst *NewCall; 991 if (SplatValue) { 992 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, 993 MaybeAlign(StoreAlignment)); 994 } else { 995 // Everything is emitted in default address space 996 Type *Int8PtrTy = DestInt8PtrTy; 997 998 Module *M = TheStore->getModule(); 999 StringRef FuncName = "memset_pattern16"; 1000 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(), 1001 Int8PtrTy, Int8PtrTy, IntIdxTy); 1002 inferLibFuncAttributes(M, FuncName, *TLI); 1003 1004 // Otherwise we should form a memset_pattern16. PatternValue is known to be 1005 // an constant array of 16-bytes. Plop the value into a mergable global. 1006 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 1007 GlobalValue::PrivateLinkage, 1008 PatternValue, ".memset_pattern"); 1009 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. 1010 GV->setAlignment(Align(16)); 1011 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 1012 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 1013 } 1014 NewCall->setDebugLoc(TheStore->getDebugLoc()); 1015 1016 if (MSSAU) { 1017 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1018 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1019 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1020 } 1021 1022 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 1023 << " from store to: " << *Ev << " at: " << *TheStore 1024 << "\n"); 1025 1026 ORE.emit([&]() { 1027 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStridedStore", 1028 NewCall->getDebugLoc(), Preheader) 1029 << "Transformed loop-strided store into a call to " 1030 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1031 << "() function"; 1032 }); 1033 1034 // Okay, the memset has been formed. Zap the original store and anything that 1035 // feeds into it. 1036 for (auto *I : Stores) { 1037 if (MSSAU) 1038 MSSAU->removeMemoryAccess(I, true); 1039 deleteDeadInstruction(I); 1040 } 1041 if (MSSAU && VerifyMemorySSA) 1042 MSSAU->getMemorySSA()->verifyMemorySSA(); 1043 ++NumMemSet; 1044 EVC.commit(); 1045 return true; 1046 } 1047 1048 /// If the stored value is a strided load in the same loop with the same stride 1049 /// this may be transformable into a memcpy. This kicks in for stuff like 1050 /// for (i) A[i] = B[i]; 1051 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, 1052 const SCEV *BECount) { 1053 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores."); 1054 1055 Value *StorePtr = SI->getPointerOperand(); 1056 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 1057 APInt Stride = getStoreStride(StoreEv); 1058 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 1059 bool NegStride = StoreSize == -Stride; 1060 1061 // The store must be feeding a non-volatile load. 1062 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 1063 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads."); 1064 1065 // See if the pointer expression is an AddRec like {base,+,1} on the current 1066 // loop, which indicates a strided load. If we have something else, it's a 1067 // random load we can't handle. 1068 const SCEVAddRecExpr *LoadEv = 1069 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 1070 1071 // The trip count of the loop and the base pointer of the addrec SCEV is 1072 // guaranteed to be loop invariant, which means that it should dominate the 1073 // header. This allows us to insert code for it in the preheader. 1074 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1075 IRBuilder<> Builder(Preheader->getTerminator()); 1076 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1077 1078 ExpandedValuesCleaner EVC(Expander, TLI); 1079 1080 bool Changed = false; 1081 const SCEV *StrStart = StoreEv->getStart(); 1082 unsigned StrAS = SI->getPointerAddressSpace(); 1083 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS)); 1084 1085 // Handle negative strided loops. 1086 if (NegStride) 1087 StrStart = getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSize, SE); 1088 1089 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 1090 // this into a memcpy in the loop preheader now if we want. However, this 1091 // would be unsafe to do if there is anything else in the loop that may read 1092 // or write the memory region we're storing to. This includes the load that 1093 // feeds the stores. Check for an alias by generating the base address and 1094 // checking everything. 1095 Value *StoreBasePtr = Expander.expandCodeFor( 1096 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); 1097 EVC.add(StoreBasePtr); 1098 1099 // From here on out, conservatively report to the pass manager that we've 1100 // changed the IR, even if we later clean up these added instructions. There 1101 // may be structural differences e.g. in the order of use lists not accounted 1102 // for in just a textual dump of the IR. This is written as a variable, even 1103 // though statically all the places this dominates could be replaced with 1104 // 'true', with the hope that anyone trying to be clever / "more precise" with 1105 // the return value will read this comment, and leave them alone. 1106 Changed = true; 1107 1108 SmallPtrSet<Instruction *, 1> Stores; 1109 Stores.insert(SI); 1110 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1111 StoreSize, *AA, Stores)) 1112 return Changed; 1113 1114 const SCEV *LdStart = LoadEv->getStart(); 1115 unsigned LdAS = LI->getPointerAddressSpace(); 1116 1117 // Handle negative strided loops. 1118 if (NegStride) 1119 LdStart = getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSize, SE); 1120 1121 // For a memcpy, we have to make sure that the input array is not being 1122 // mutated by the loop. 1123 Value *LoadBasePtr = Expander.expandCodeFor( 1124 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); 1125 EVC.add(LoadBasePtr); 1126 1127 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, 1128 StoreSize, *AA, Stores)) 1129 return Changed; 1130 1131 if (avoidLIRForMultiBlockLoop()) 1132 return Changed; 1133 1134 // Okay, everything is safe, we can transform this! 1135 1136 const SCEV *NumBytesS = 1137 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE); 1138 1139 Value *NumBytes = 1140 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1141 EVC.add(NumBytes); 1142 1143 CallInst *NewCall = nullptr; 1144 // Check whether to generate an unordered atomic memcpy: 1145 // If the load or store are atomic, then they must necessarily be unordered 1146 // by previous checks. 1147 if (!SI->isAtomic() && !LI->isAtomic()) 1148 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr, 1149 LI->getAlign(), NumBytes); 1150 else { 1151 // We cannot allow unaligned ops for unordered load/store, so reject 1152 // anything where the alignment isn't at least the element size. 1153 const Align StoreAlign = SI->getAlign(); 1154 const Align LoadAlign = LI->getAlign(); 1155 if (StoreAlign < StoreSize || LoadAlign < StoreSize) 1156 return Changed; 1157 1158 // If the element.atomic memcpy is not lowered into explicit 1159 // loads/stores later, then it will be lowered into an element-size 1160 // specific lib call. If the lib call doesn't exist for our store size, then 1161 // we shouldn't generate the memcpy. 1162 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize()) 1163 return Changed; 1164 1165 // Create the call. 1166 // Note that unordered atomic loads/stores are *required* by the spec to 1167 // have an alignment but non-atomic loads/stores may not. 1168 NewCall = Builder.CreateElementUnorderedAtomicMemCpy( 1169 StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign, NumBytes, 1170 StoreSize); 1171 } 1172 NewCall->setDebugLoc(SI->getDebugLoc()); 1173 1174 if (MSSAU) { 1175 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1176 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1177 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1178 } 1179 1180 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" 1181 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 1182 << " from store ptr=" << *StoreEv << " at: " << *SI 1183 << "\n"); 1184 1185 ORE.emit([&]() { 1186 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad", 1187 NewCall->getDebugLoc(), Preheader) 1188 << "Formed a call to " 1189 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1190 << "() function"; 1191 }); 1192 1193 // Okay, the memcpy has been formed. Zap the original store and anything that 1194 // feeds into it. 1195 if (MSSAU) 1196 MSSAU->removeMemoryAccess(SI, true); 1197 deleteDeadInstruction(SI); 1198 if (MSSAU && VerifyMemorySSA) 1199 MSSAU->getMemorySSA()->verifyMemorySSA(); 1200 ++NumMemCpy; 1201 EVC.commit(); 1202 return true; 1203 } 1204 1205 // When compiling for codesize we avoid idiom recognition for a multi-block loop 1206 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. 1207 // 1208 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, 1209 bool IsLoopMemset) { 1210 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { 1211 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) { 1212 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() 1213 << " : LIR " << (IsMemset ? "Memset" : "Memcpy") 1214 << " avoided: multi-block top-level loop\n"); 1215 return true; 1216 } 1217 } 1218 1219 return false; 1220 } 1221 1222 bool LoopIdiomRecognize::runOnNoncountableLoop() { 1223 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 1224 << CurLoop->getHeader()->getParent()->getName() 1225 << "] Noncountable Loop %" 1226 << CurLoop->getHeader()->getName() << "\n"); 1227 1228 return recognizePopcount() || recognizeAndInsertFFS(); 1229 } 1230 1231 /// Check if the given conditional branch is based on the comparison between 1232 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is 1233 /// true), the control yields to the loop entry. If the branch matches the 1234 /// behavior, the variable involved in the comparison is returned. This function 1235 /// will be called to see if the precondition and postcondition of the loop are 1236 /// in desirable form. 1237 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry, 1238 bool JmpOnZero = false) { 1239 if (!BI || !BI->isConditional()) 1240 return nullptr; 1241 1242 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1243 if (!Cond) 1244 return nullptr; 1245 1246 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 1247 if (!CmpZero || !CmpZero->isZero()) 1248 return nullptr; 1249 1250 BasicBlock *TrueSucc = BI->getSuccessor(0); 1251 BasicBlock *FalseSucc = BI->getSuccessor(1); 1252 if (JmpOnZero) 1253 std::swap(TrueSucc, FalseSucc); 1254 1255 ICmpInst::Predicate Pred = Cond->getPredicate(); 1256 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) || 1257 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry)) 1258 return Cond->getOperand(0); 1259 1260 return nullptr; 1261 } 1262 1263 // Check if the recurrence variable `VarX` is in the right form to create 1264 // the idiom. Returns the value coerced to a PHINode if so. 1265 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX, 1266 BasicBlock *LoopEntry) { 1267 auto *PhiX = dyn_cast<PHINode>(VarX); 1268 if (PhiX && PhiX->getParent() == LoopEntry && 1269 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX)) 1270 return PhiX; 1271 return nullptr; 1272 } 1273 1274 /// Return true iff the idiom is detected in the loop. 1275 /// 1276 /// Additionally: 1277 /// 1) \p CntInst is set to the instruction counting the population bit. 1278 /// 2) \p CntPhi is set to the corresponding phi node. 1279 /// 3) \p Var is set to the value whose population bits are being counted. 1280 /// 1281 /// The core idiom we are trying to detect is: 1282 /// \code 1283 /// if (x0 != 0) 1284 /// goto loop-exit // the precondition of the loop 1285 /// cnt0 = init-val; 1286 /// do { 1287 /// x1 = phi (x0, x2); 1288 /// cnt1 = phi(cnt0, cnt2); 1289 /// 1290 /// cnt2 = cnt1 + 1; 1291 /// ... 1292 /// x2 = x1 & (x1 - 1); 1293 /// ... 1294 /// } while(x != 0); 1295 /// 1296 /// loop-exit: 1297 /// \endcode 1298 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 1299 Instruction *&CntInst, PHINode *&CntPhi, 1300 Value *&Var) { 1301 // step 1: Check to see if the look-back branch match this pattern: 1302 // "if (a!=0) goto loop-entry". 1303 BasicBlock *LoopEntry; 1304 Instruction *DefX2, *CountInst; 1305 Value *VarX1, *VarX0; 1306 PHINode *PhiX, *CountPhi; 1307 1308 DefX2 = CountInst = nullptr; 1309 VarX1 = VarX0 = nullptr; 1310 PhiX = CountPhi = nullptr; 1311 LoopEntry = *(CurLoop->block_begin()); 1312 1313 // step 1: Check if the loop-back branch is in desirable form. 1314 { 1315 if (Value *T = matchCondition( 1316 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1317 DefX2 = dyn_cast<Instruction>(T); 1318 else 1319 return false; 1320 } 1321 1322 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 1323 { 1324 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 1325 return false; 1326 1327 BinaryOperator *SubOneOp; 1328 1329 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 1330 VarX1 = DefX2->getOperand(1); 1331 else { 1332 VarX1 = DefX2->getOperand(0); 1333 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 1334 } 1335 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1) 1336 return false; 1337 1338 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1)); 1339 if (!Dec || 1340 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) || 1341 (SubOneOp->getOpcode() == Instruction::Add && 1342 Dec->isMinusOne()))) { 1343 return false; 1344 } 1345 } 1346 1347 // step 3: Check the recurrence of variable X 1348 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry); 1349 if (!PhiX) 1350 return false; 1351 1352 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 1353 { 1354 CountInst = nullptr; 1355 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1356 IterE = LoopEntry->end(); 1357 Iter != IterE; Iter++) { 1358 Instruction *Inst = &*Iter; 1359 if (Inst->getOpcode() != Instruction::Add) 1360 continue; 1361 1362 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1363 if (!Inc || !Inc->isOne()) 1364 continue; 1365 1366 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1367 if (!Phi) 1368 continue; 1369 1370 // Check if the result of the instruction is live of the loop. 1371 bool LiveOutLoop = false; 1372 for (User *U : Inst->users()) { 1373 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 1374 LiveOutLoop = true; 1375 break; 1376 } 1377 } 1378 1379 if (LiveOutLoop) { 1380 CountInst = Inst; 1381 CountPhi = Phi; 1382 break; 1383 } 1384 } 1385 1386 if (!CountInst) 1387 return false; 1388 } 1389 1390 // step 5: check if the precondition is in this form: 1391 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 1392 { 1393 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1394 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 1395 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 1396 return false; 1397 1398 CntInst = CountInst; 1399 CntPhi = CountPhi; 1400 Var = T; 1401 } 1402 1403 return true; 1404 } 1405 1406 /// Return true if the idiom is detected in the loop. 1407 /// 1408 /// Additionally: 1409 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) 1410 /// or nullptr if there is no such. 1411 /// 2) \p CntPhi is set to the corresponding phi node 1412 /// or nullptr if there is no such. 1413 /// 3) \p Var is set to the value whose CTLZ could be used. 1414 /// 4) \p DefX is set to the instruction calculating Loop exit condition. 1415 /// 1416 /// The core idiom we are trying to detect is: 1417 /// \code 1418 /// if (x0 == 0) 1419 /// goto loop-exit // the precondition of the loop 1420 /// cnt0 = init-val; 1421 /// do { 1422 /// x = phi (x0, x.next); //PhiX 1423 /// cnt = phi(cnt0, cnt.next); 1424 /// 1425 /// cnt.next = cnt + 1; 1426 /// ... 1427 /// x.next = x >> 1; // DefX 1428 /// ... 1429 /// } while(x.next != 0); 1430 /// 1431 /// loop-exit: 1432 /// \endcode 1433 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, 1434 Intrinsic::ID &IntrinID, Value *&InitX, 1435 Instruction *&CntInst, PHINode *&CntPhi, 1436 Instruction *&DefX) { 1437 BasicBlock *LoopEntry; 1438 Value *VarX = nullptr; 1439 1440 DefX = nullptr; 1441 CntInst = nullptr; 1442 CntPhi = nullptr; 1443 LoopEntry = *(CurLoop->block_begin()); 1444 1445 // step 1: Check if the loop-back branch is in desirable form. 1446 if (Value *T = matchCondition( 1447 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1448 DefX = dyn_cast<Instruction>(T); 1449 else 1450 return false; 1451 1452 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1" 1453 if (!DefX || !DefX->isShift()) 1454 return false; 1455 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz : 1456 Intrinsic::ctlz; 1457 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)); 1458 if (!Shft || !Shft->isOne()) 1459 return false; 1460 VarX = DefX->getOperand(0); 1461 1462 // step 3: Check the recurrence of variable X 1463 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry); 1464 if (!PhiX) 1465 return false; 1466 1467 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader()); 1468 1469 // Make sure the initial value can't be negative otherwise the ashr in the 1470 // loop might never reach zero which would make the loop infinite. 1471 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL)) 1472 return false; 1473 1474 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 1475 // TODO: We can skip the step. If loop trip count is known (CTLZ), 1476 // then all uses of "cnt.next" could be optimized to the trip count 1477 // plus "cnt0". Currently it is not optimized. 1478 // This step could be used to detect POPCNT instruction: 1479 // cnt.next = cnt + (x.next & 1) 1480 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1481 IterE = LoopEntry->end(); 1482 Iter != IterE; Iter++) { 1483 Instruction *Inst = &*Iter; 1484 if (Inst->getOpcode() != Instruction::Add) 1485 continue; 1486 1487 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1488 if (!Inc || !Inc->isOne()) 1489 continue; 1490 1491 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1492 if (!Phi) 1493 continue; 1494 1495 CntInst = Inst; 1496 CntPhi = Phi; 1497 break; 1498 } 1499 if (!CntInst) 1500 return false; 1501 1502 return true; 1503 } 1504 1505 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop 1506 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new 1507 /// trip count returns true; otherwise, returns false. 1508 bool LoopIdiomRecognize::recognizeAndInsertFFS() { 1509 // Give up if the loop has multiple blocks or multiple backedges. 1510 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1511 return false; 1512 1513 Intrinsic::ID IntrinID; 1514 Value *InitX; 1515 Instruction *DefX = nullptr; 1516 PHINode *CntPhi = nullptr; 1517 Instruction *CntInst = nullptr; 1518 // Help decide if transformation is profitable. For ShiftUntilZero idiom, 1519 // this is always 6. 1520 size_t IdiomCanonicalSize = 6; 1521 1522 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, 1523 CntInst, CntPhi, DefX)) 1524 return false; 1525 1526 bool IsCntPhiUsedOutsideLoop = false; 1527 for (User *U : CntPhi->users()) 1528 if (!CurLoop->contains(cast<Instruction>(U))) { 1529 IsCntPhiUsedOutsideLoop = true; 1530 break; 1531 } 1532 bool IsCntInstUsedOutsideLoop = false; 1533 for (User *U : CntInst->users()) 1534 if (!CurLoop->contains(cast<Instruction>(U))) { 1535 IsCntInstUsedOutsideLoop = true; 1536 break; 1537 } 1538 // If both CntInst and CntPhi are used outside the loop the profitability 1539 // is questionable. 1540 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) 1541 return false; 1542 1543 // For some CPUs result of CTLZ(X) intrinsic is undefined 1544 // when X is 0. If we can not guarantee X != 0, we need to check this 1545 // when expand. 1546 bool ZeroCheck = false; 1547 // It is safe to assume Preheader exist as it was checked in 1548 // parent function RunOnLoop. 1549 BasicBlock *PH = CurLoop->getLoopPreheader(); 1550 1551 // If we are using the count instruction outside the loop, make sure we 1552 // have a zero check as a precondition. Without the check the loop would run 1553 // one iteration for before any check of the input value. This means 0 and 1 1554 // would have identical behavior in the original loop and thus 1555 if (!IsCntPhiUsedOutsideLoop) { 1556 auto *PreCondBB = PH->getSinglePredecessor(); 1557 if (!PreCondBB) 1558 return false; 1559 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1560 if (!PreCondBI) 1561 return false; 1562 if (matchCondition(PreCondBI, PH) != InitX) 1563 return false; 1564 ZeroCheck = true; 1565 } 1566 1567 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always 1568 // profitable if we delete the loop. 1569 1570 // the loop has only 6 instructions: 1571 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] 1572 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] 1573 // %shr = ashr %n.addr.0, 1 1574 // %tobool = icmp eq %shr, 0 1575 // %inc = add nsw %i.0, 1 1576 // br i1 %tobool 1577 1578 const Value *Args[] = { 1579 InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext()) 1580 : ConstantInt::getFalse(InitX->getContext())}; 1581 1582 // @llvm.dbg doesn't count as they have no semantic effect. 1583 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug(); 1584 uint32_t HeaderSize = 1585 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end()); 1586 1587 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args); 1588 int Cost = 1589 TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency); 1590 if (HeaderSize != IdiomCanonicalSize && 1591 Cost > TargetTransformInfo::TCC_Basic) 1592 return false; 1593 1594 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX, 1595 DefX->getDebugLoc(), ZeroCheck, 1596 IsCntPhiUsedOutsideLoop); 1597 return true; 1598 } 1599 1600 /// Recognizes a population count idiom in a non-countable loop. 1601 /// 1602 /// If detected, transforms the relevant code to issue the popcount intrinsic 1603 /// function call, and returns true; otherwise, returns false. 1604 bool LoopIdiomRecognize::recognizePopcount() { 1605 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 1606 return false; 1607 1608 // Counting population are usually conducted by few arithmetic instructions. 1609 // Such instructions can be easily "absorbed" by vacant slots in a 1610 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 1611 // in a compact loop. 1612 1613 // Give up if the loop has multiple blocks or multiple backedges. 1614 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1615 return false; 1616 1617 BasicBlock *LoopBody = *(CurLoop->block_begin()); 1618 if (LoopBody->size() >= 20) { 1619 // The loop is too big, bail out. 1620 return false; 1621 } 1622 1623 // It should have a preheader containing nothing but an unconditional branch. 1624 BasicBlock *PH = CurLoop->getLoopPreheader(); 1625 if (!PH || &PH->front() != PH->getTerminator()) 1626 return false; 1627 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 1628 if (!EntryBI || EntryBI->isConditional()) 1629 return false; 1630 1631 // It should have a precondition block where the generated popcount intrinsic 1632 // function can be inserted. 1633 auto *PreCondBB = PH->getSinglePredecessor(); 1634 if (!PreCondBB) 1635 return false; 1636 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1637 if (!PreCondBI || PreCondBI->isUnconditional()) 1638 return false; 1639 1640 Instruction *CntInst; 1641 PHINode *CntPhi; 1642 Value *Val; 1643 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 1644 return false; 1645 1646 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 1647 return true; 1648 } 1649 1650 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1651 const DebugLoc &DL) { 1652 Value *Ops[] = {Val}; 1653 Type *Tys[] = {Val->getType()}; 1654 1655 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1656 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 1657 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1658 CI->setDebugLoc(DL); 1659 1660 return CI; 1661 } 1662 1663 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1664 const DebugLoc &DL, bool ZeroCheck, 1665 Intrinsic::ID IID) { 1666 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()}; 1667 Type *Tys[] = {Val->getType()}; 1668 1669 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1670 Function *Func = Intrinsic::getDeclaration(M, IID, Tys); 1671 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1672 CI->setDebugLoc(DL); 1673 1674 return CI; 1675 } 1676 1677 /// Transform the following loop (Using CTLZ, CTTZ is similar): 1678 /// loop: 1679 /// CntPhi = PHI [Cnt0, CntInst] 1680 /// PhiX = PHI [InitX, DefX] 1681 /// CntInst = CntPhi + 1 1682 /// DefX = PhiX >> 1 1683 /// LOOP_BODY 1684 /// Br: loop if (DefX != 0) 1685 /// Use(CntPhi) or Use(CntInst) 1686 /// 1687 /// Into: 1688 /// If CntPhi used outside the loop: 1689 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) 1690 /// Count = CountPrev + 1 1691 /// else 1692 /// Count = BitWidth(InitX) - CTLZ(InitX) 1693 /// loop: 1694 /// CntPhi = PHI [Cnt0, CntInst] 1695 /// PhiX = PHI [InitX, DefX] 1696 /// PhiCount = PHI [Count, Dec] 1697 /// CntInst = CntPhi + 1 1698 /// DefX = PhiX >> 1 1699 /// Dec = PhiCount - 1 1700 /// LOOP_BODY 1701 /// Br: loop if (Dec != 0) 1702 /// Use(CountPrev + Cnt0) // Use(CntPhi) 1703 /// or 1704 /// Use(Count + Cnt0) // Use(CntInst) 1705 /// 1706 /// If LOOP_BODY is empty the loop will be deleted. 1707 /// If CntInst and DefX are not used in LOOP_BODY they will be removed. 1708 void LoopIdiomRecognize::transformLoopToCountable( 1709 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst, 1710 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL, 1711 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { 1712 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator()); 1713 1714 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block 1715 IRBuilder<> Builder(PreheaderBr); 1716 Builder.SetCurrentDebugLocation(DL); 1717 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext; 1718 1719 // Count = BitWidth - CTLZ(InitX); 1720 // If there are uses of CntPhi create: 1721 // CountPrev = BitWidth - CTLZ(InitX >> 1); 1722 if (IsCntPhiUsedOutsideLoop) { 1723 if (DefX->getOpcode() == Instruction::AShr) 1724 InitXNext = 1725 Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1)); 1726 else if (DefX->getOpcode() == Instruction::LShr) 1727 InitXNext = 1728 Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1)); 1729 else if (DefX->getOpcode() == Instruction::Shl) // cttz 1730 InitXNext = 1731 Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1)); 1732 else 1733 llvm_unreachable("Unexpected opcode!"); 1734 } else 1735 InitXNext = InitX; 1736 FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID); 1737 Count = Builder.CreateSub( 1738 ConstantInt::get(FFS->getType(), 1739 FFS->getType()->getIntegerBitWidth()), 1740 FFS); 1741 if (IsCntPhiUsedOutsideLoop) { 1742 CountPrev = Count; 1743 Count = Builder.CreateAdd( 1744 CountPrev, 1745 ConstantInt::get(CountPrev->getType(), 1)); 1746 } 1747 1748 NewCount = Builder.CreateZExtOrTrunc( 1749 IsCntPhiUsedOutsideLoop ? CountPrev : Count, 1750 cast<IntegerType>(CntInst->getType())); 1751 1752 // If the counter's initial value is not zero, insert Add Inst. 1753 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); 1754 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 1755 if (!InitConst || !InitConst->isZero()) 1756 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 1757 1758 // Step 2: Insert new IV and loop condition: 1759 // loop: 1760 // ... 1761 // PhiCount = PHI [Count, Dec] 1762 // ... 1763 // Dec = PhiCount - 1 1764 // ... 1765 // Br: loop if (Dec != 0) 1766 BasicBlock *Body = *(CurLoop->block_begin()); 1767 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 1768 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1769 Type *Ty = Count->getType(); 1770 1771 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1772 1773 Builder.SetInsertPoint(LbCond); 1774 Instruction *TcDec = cast<Instruction>( 1775 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1776 "tcdec", false, true)); 1777 1778 TcPhi->addIncoming(Count, Preheader); 1779 TcPhi->addIncoming(TcDec, Body); 1780 1781 CmpInst::Predicate Pred = 1782 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 1783 LbCond->setPredicate(Pred); 1784 LbCond->setOperand(0, TcDec); 1785 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1786 1787 // Step 3: All the references to the original counter outside 1788 // the loop are replaced with the NewCount 1789 if (IsCntPhiUsedOutsideLoop) 1790 CntPhi->replaceUsesOutsideBlock(NewCount, Body); 1791 else 1792 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1793 1794 // step 4: Forget the "non-computable" trip-count SCEV associated with the 1795 // loop. The loop would otherwise not be deleted even if it becomes empty. 1796 SE->forgetLoop(CurLoop); 1797 } 1798 1799 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 1800 Instruction *CntInst, 1801 PHINode *CntPhi, Value *Var) { 1802 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 1803 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator()); 1804 const DebugLoc &DL = CntInst->getDebugLoc(); 1805 1806 // Assuming before transformation, the loop is following: 1807 // if (x) // the precondition 1808 // do { cnt++; x &= x - 1; } while(x); 1809 1810 // Step 1: Insert the ctpop instruction at the end of the precondition block 1811 IRBuilder<> Builder(PreCondBr); 1812 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 1813 { 1814 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 1815 NewCount = PopCntZext = 1816 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 1817 1818 if (NewCount != PopCnt) 1819 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1820 1821 // TripCnt is exactly the number of iterations the loop has 1822 TripCnt = NewCount; 1823 1824 // If the population counter's initial value is not zero, insert Add Inst. 1825 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 1826 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 1827 if (!InitConst || !InitConst->isZero()) { 1828 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 1829 (cast<Instruction>(NewCount))->setDebugLoc(DL); 1830 } 1831 } 1832 1833 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 1834 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 1835 // function would be partial dead code, and downstream passes will drag 1836 // it back from the precondition block to the preheader. 1837 { 1838 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 1839 1840 Value *Opnd0 = PopCntZext; 1841 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 1842 if (PreCond->getOperand(0) != Var) 1843 std::swap(Opnd0, Opnd1); 1844 1845 ICmpInst *NewPreCond = cast<ICmpInst>( 1846 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 1847 PreCondBr->setCondition(NewPreCond); 1848 1849 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 1850 } 1851 1852 // Step 3: Note that the population count is exactly the trip count of the 1853 // loop in question, which enable us to convert the loop from noncountable 1854 // loop into a countable one. The benefit is twofold: 1855 // 1856 // - If the loop only counts population, the entire loop becomes dead after 1857 // the transformation. It is a lot easier to prove a countable loop dead 1858 // than to prove a noncountable one. (In some C dialects, an infinite loop 1859 // isn't dead even if it computes nothing useful. In general, DCE needs 1860 // to prove a noncountable loop finite before safely delete it.) 1861 // 1862 // - If the loop also performs something else, it remains alive. 1863 // Since it is transformed to countable form, it can be aggressively 1864 // optimized by some optimizations which are in general not applicable 1865 // to a noncountable loop. 1866 // 1867 // After this step, this loop (conceptually) would look like following: 1868 // newcnt = __builtin_ctpop(x); 1869 // t = newcnt; 1870 // if (x) 1871 // do { cnt++; x &= x-1; t--) } while (t > 0); 1872 BasicBlock *Body = *(CurLoop->block_begin()); 1873 { 1874 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 1875 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 1876 Type *Ty = TripCnt->getType(); 1877 1878 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 1879 1880 Builder.SetInsertPoint(LbCond); 1881 Instruction *TcDec = cast<Instruction>( 1882 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 1883 "tcdec", false, true)); 1884 1885 TcPhi->addIncoming(TripCnt, PreHead); 1886 TcPhi->addIncoming(TcDec, Body); 1887 1888 CmpInst::Predicate Pred = 1889 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 1890 LbCond->setPredicate(Pred); 1891 LbCond->setOperand(0, TcDec); 1892 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 1893 } 1894 1895 // Step 4: All the references to the original population counter outside 1896 // the loop are replaced with the NewCount -- the value returned from 1897 // __builtin_ctpop(). 1898 CntInst->replaceUsesOutsideBlock(NewCount, Body); 1899 1900 // step 5: Forget the "non-computable" trip-count SCEV associated with the 1901 // loop. The loop would otherwise not be deleted even if it becomes empty. 1902 SE->forgetLoop(CurLoop); 1903 } 1904