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, 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/CmpInstAnalysis.h" 51 #include "llvm/Analysis/LoopAccessAnalysis.h" 52 #include "llvm/Analysis/LoopInfo.h" 53 #include "llvm/Analysis/LoopPass.h" 54 #include "llvm/Analysis/MemoryLocation.h" 55 #include "llvm/Analysis/MemorySSA.h" 56 #include "llvm/Analysis/MemorySSAUpdater.h" 57 #include "llvm/Analysis/MustExecute.h" 58 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 59 #include "llvm/Analysis/ScalarEvolution.h" 60 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/Analysis/ValueTracking.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Dominators.h" 72 #include "llvm/IR/GlobalValue.h" 73 #include "llvm/IR/GlobalVariable.h" 74 #include "llvm/IR/IRBuilder.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instruction.h" 77 #include "llvm/IR/Instructions.h" 78 #include "llvm/IR/IntrinsicInst.h" 79 #include "llvm/IR/Intrinsics.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PassManager.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/IR/ValueHandle.h" 88 #include "llvm/InitializePasses.h" 89 #include "llvm/Pass.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/InstructionCost.h" 94 #include "llvm/Support/raw_ostream.h" 95 #include "llvm/Transforms/Scalar.h" 96 #include "llvm/Transforms/Utils/BuildLibCalls.h" 97 #include "llvm/Transforms/Utils/Local.h" 98 #include "llvm/Transforms/Utils/LoopUtils.h" 99 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 100 #include <algorithm> 101 #include <cassert> 102 #include <cstdint> 103 #include <utility> 104 #include <vector> 105 106 using namespace llvm; 107 108 #define DEBUG_TYPE "loop-idiom" 109 110 STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); 111 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); 112 STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores"); 113 STATISTIC( 114 NumShiftUntilBitTest, 115 "Number of uncountable loops recognized as 'shift until bitttest' idiom"); 116 STATISTIC(NumShiftUntilZero, 117 "Number of uncountable loops recognized as 'shift until zero' idiom"); 118 119 bool DisableLIRP::All; 120 static cl::opt<bool, true> 121 DisableLIRPAll("disable-" DEBUG_TYPE "-all", 122 cl::desc("Options to disable Loop Idiom Recognize Pass."), 123 cl::location(DisableLIRP::All), cl::init(false), 124 cl::ReallyHidden); 125 126 bool DisableLIRP::Memset; 127 static cl::opt<bool, true> 128 DisableLIRPMemset("disable-" DEBUG_TYPE "-memset", 129 cl::desc("Proceed with loop idiom recognize pass, but do " 130 "not convert loop(s) to memset."), 131 cl::location(DisableLIRP::Memset), cl::init(false), 132 cl::ReallyHidden); 133 134 bool DisableLIRP::Memcpy; 135 static cl::opt<bool, true> 136 DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy", 137 cl::desc("Proceed with loop idiom recognize pass, but do " 138 "not convert loop(s) to memcpy."), 139 cl::location(DisableLIRP::Memcpy), cl::init(false), 140 cl::ReallyHidden); 141 142 static cl::opt<bool> UseLIRCodeSizeHeurs( 143 "use-lir-code-size-heurs", 144 cl::desc("Use loop idiom recognition code size heuristics when compiling" 145 "with -Os/-Oz"), 146 cl::init(true), cl::Hidden); 147 148 namespace { 149 150 class LoopIdiomRecognize { 151 Loop *CurLoop = nullptr; 152 AliasAnalysis *AA; 153 DominatorTree *DT; 154 LoopInfo *LI; 155 ScalarEvolution *SE; 156 TargetLibraryInfo *TLI; 157 const TargetTransformInfo *TTI; 158 const DataLayout *DL; 159 OptimizationRemarkEmitter &ORE; 160 bool ApplyCodeSizeHeuristics; 161 std::unique_ptr<MemorySSAUpdater> MSSAU; 162 163 public: 164 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 165 LoopInfo *LI, ScalarEvolution *SE, 166 TargetLibraryInfo *TLI, 167 const TargetTransformInfo *TTI, MemorySSA *MSSA, 168 const DataLayout *DL, 169 OptimizationRemarkEmitter &ORE) 170 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) { 171 if (MSSA) 172 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 173 } 174 175 bool runOnLoop(Loop *L); 176 177 private: 178 using StoreList = SmallVector<StoreInst *, 8>; 179 using StoreListMap = MapVector<Value *, StoreList>; 180 181 StoreListMap StoreRefsForMemset; 182 StoreListMap StoreRefsForMemsetPattern; 183 StoreList StoreRefsForMemcpy; 184 bool HasMemset; 185 bool HasMemsetPattern; 186 bool HasMemcpy; 187 188 /// Return code for isLegalStore() 189 enum LegalStoreKind { 190 None = 0, 191 Memset, 192 MemsetPattern, 193 Memcpy, 194 UnorderedAtomicMemcpy, 195 DontUse // Dummy retval never to be used. Allows catching errors in retval 196 // handling. 197 }; 198 199 /// \name Countable Loop Idiom Handling 200 /// @{ 201 202 bool runOnCountableLoop(); 203 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, 204 SmallVectorImpl<BasicBlock *> &ExitBlocks); 205 206 void collectStores(BasicBlock *BB); 207 LegalStoreKind isLegalStore(StoreInst *SI); 208 enum class ForMemset { No, Yes }; 209 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, 210 ForMemset For); 211 212 template <typename MemInst> 213 bool processLoopMemIntrinsic( 214 BasicBlock *BB, 215 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *), 216 const SCEV *BECount); 217 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount); 218 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); 219 220 bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV, 221 MaybeAlign StoreAlignment, Value *StoredVal, 222 Instruction *TheStore, 223 SmallPtrSetImpl<Instruction *> &Stores, 224 const SCEVAddRecExpr *Ev, const SCEV *BECount, 225 bool IsNegStride, bool IsLoopMemset = false); 226 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); 227 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr, 228 const SCEV *StoreSize, MaybeAlign StoreAlign, 229 MaybeAlign LoadAlign, Instruction *TheStore, 230 Instruction *TheLoad, 231 const SCEVAddRecExpr *StoreEv, 232 const SCEVAddRecExpr *LoadEv, 233 const SCEV *BECount); 234 bool avoidLIRForMultiBlockLoop(bool IsMemset = false, 235 bool IsLoopMemset = false); 236 237 /// @} 238 /// \name Noncountable Loop Idiom Handling 239 /// @{ 240 241 bool runOnNoncountableLoop(); 242 243 bool recognizePopcount(); 244 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, 245 PHINode *CntPhi, Value *Var); 246 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz 247 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB, 248 Instruction *CntInst, PHINode *CntPhi, 249 Value *Var, Instruction *DefX, 250 const DebugLoc &DL, bool ZeroCheck, 251 bool IsCntPhiUsedOutsideLoop); 252 253 bool recognizeShiftUntilBitTest(); 254 bool recognizeShiftUntilZero(); 255 256 /// @} 257 }; 258 259 class LoopIdiomRecognizeLegacyPass : public LoopPass { 260 public: 261 static char ID; 262 263 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 264 initializeLoopIdiomRecognizeLegacyPassPass( 265 *PassRegistry::getPassRegistry()); 266 } 267 268 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 269 if (DisableLIRP::All) 270 return false; 271 272 if (skipLoop(L)) 273 return false; 274 275 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 276 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 277 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 278 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 279 TargetLibraryInfo *TLI = 280 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 281 *L->getHeader()->getParent()); 282 const TargetTransformInfo *TTI = 283 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 284 *L->getHeader()->getParent()); 285 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); 286 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 287 MemorySSA *MSSA = nullptr; 288 if (MSSAAnalysis) 289 MSSA = &MSSAAnalysis->getMSSA(); 290 291 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 292 // pass. Function analyses need to be preserved across loop transformations 293 // but ORE cannot be preserved (see comment before the pass definition). 294 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 295 296 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE); 297 return LIR.runOnLoop(L); 298 } 299 300 /// This transformation requires natural loop information & requires that 301 /// loop preheaders be inserted into the CFG. 302 void getAnalysisUsage(AnalysisUsage &AU) const override { 303 AU.addRequired<TargetLibraryInfoWrapperPass>(); 304 AU.addRequired<TargetTransformInfoWrapperPass>(); 305 AU.addPreserved<MemorySSAWrapperPass>(); 306 getLoopAnalysisUsage(AU); 307 } 308 }; 309 310 } // end anonymous namespace 311 312 char LoopIdiomRecognizeLegacyPass::ID = 0; 313 314 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, 315 LoopStandardAnalysisResults &AR, 316 LPMUpdater &) { 317 if (DisableLIRP::All) 318 return PreservedAnalyses::all(); 319 320 const auto *DL = &L.getHeader()->getModule()->getDataLayout(); 321 322 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis 323 // pass. Function analyses need to be preserved across loop transformations 324 // but ORE cannot be preserved (see comment before the pass definition). 325 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 326 327 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, 328 AR.MSSA, DL, ORE); 329 if (!LIR.runOnLoop(&L)) 330 return PreservedAnalyses::all(); 331 332 auto PA = getLoopPassPreservedAnalyses(); 333 if (AR.MSSA) 334 PA.preserve<MemorySSAAnalysis>(); 335 return PA; 336 } 337 338 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", 339 "Recognize loop idioms", false, false) 340 INITIALIZE_PASS_DEPENDENCY(LoopPass) 341 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 342 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 343 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", 344 "Recognize loop idioms", false, false) 345 346 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } 347 348 static void deleteDeadInstruction(Instruction *I) { 349 I->replaceAllUsesWith(UndefValue::get(I->getType())); 350 I->eraseFromParent(); 351 } 352 353 //===----------------------------------------------------------------------===// 354 // 355 // Implementation of LoopIdiomRecognize 356 // 357 //===----------------------------------------------------------------------===// 358 359 bool LoopIdiomRecognize::runOnLoop(Loop *L) { 360 CurLoop = L; 361 // If the loop could not be converted to canonical form, it must have an 362 // indirectbr in it, just give up. 363 if (!L->getLoopPreheader()) 364 return false; 365 366 // Disable loop idiom recognition if the function's name is a common idiom. 367 StringRef Name = L->getHeader()->getParent()->getName(); 368 if (Name == "memset" || Name == "memcpy") 369 return false; 370 371 // Determine if code size heuristics need to be applied. 372 ApplyCodeSizeHeuristics = 373 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs; 374 375 HasMemset = TLI->has(LibFunc_memset); 376 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); 377 HasMemcpy = TLI->has(LibFunc_memcpy); 378 379 if (HasMemset || HasMemsetPattern || HasMemcpy) 380 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 381 return runOnCountableLoop(); 382 383 return runOnNoncountableLoop(); 384 } 385 386 bool LoopIdiomRecognize::runOnCountableLoop() { 387 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); 388 assert(!isa<SCEVCouldNotCompute>(BECount) && 389 "runOnCountableLoop() called on a loop without a predictable" 390 "backedge-taken count"); 391 392 // If this loop executes exactly one time, then it should be peeled, not 393 // optimized by this pass. 394 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 395 if (BECst->getAPInt() == 0) 396 return false; 397 398 SmallVector<BasicBlock *, 8> ExitBlocks; 399 CurLoop->getUniqueExitBlocks(ExitBlocks); 400 401 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 402 << CurLoop->getHeader()->getParent()->getName() 403 << "] Countable Loop %" << CurLoop->getHeader()->getName() 404 << "\n"); 405 406 // The following transforms hoist stores/memsets into the loop pre-header. 407 // Give up if the loop has instructions that may throw. 408 SimpleLoopSafetyInfo SafetyInfo; 409 SafetyInfo.computeLoopSafetyInfo(CurLoop); 410 if (SafetyInfo.anyBlockMayThrow()) 411 return false; 412 413 bool MadeChange = false; 414 415 // Scan all the blocks in the loop that are not in subloops. 416 for (auto *BB : CurLoop->getBlocks()) { 417 // Ignore blocks in subloops. 418 if (LI->getLoopFor(BB) != CurLoop) 419 continue; 420 421 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); 422 } 423 return MadeChange; 424 } 425 426 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { 427 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); 428 return ConstStride->getAPInt(); 429 } 430 431 /// getMemSetPatternValue - If a strided store of the specified value is safe to 432 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should 433 /// be passed in. Otherwise, return null. 434 /// 435 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these 436 /// just replicate their input array and then pass on to memset_pattern16. 437 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { 438 // FIXME: This could check for UndefValue because it can be merged into any 439 // other valid pattern. 440 441 // If the value isn't a constant, we can't promote it to being in a constant 442 // array. We could theoretically do a store to an alloca or something, but 443 // that doesn't seem worthwhile. 444 Constant *C = dyn_cast<Constant>(V); 445 if (!C) 446 return nullptr; 447 448 // Only handle simple values that are a power of two bytes in size. 449 uint64_t Size = DL->getTypeSizeInBits(V->getType()); 450 if (Size == 0 || (Size & 7) || (Size & (Size - 1))) 451 return nullptr; 452 453 // Don't care enough about darwin/ppc to implement this. 454 if (DL->isBigEndian()) 455 return nullptr; 456 457 // Convert to size in bytes. 458 Size /= 8; 459 460 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see 461 // if the top and bottom are the same (e.g. for vectors and large integers). 462 if (Size > 16) 463 return nullptr; 464 465 // If the constant is exactly 16 bytes, just use it. 466 if (Size == 16) 467 return C; 468 469 // Otherwise, we'll use an array of the constants. 470 unsigned ArraySize = 16 / Size; 471 ArrayType *AT = ArrayType::get(V->getType(), ArraySize); 472 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); 473 } 474 475 LoopIdiomRecognize::LegalStoreKind 476 LoopIdiomRecognize::isLegalStore(StoreInst *SI) { 477 // Don't touch volatile stores. 478 if (SI->isVolatile()) 479 return LegalStoreKind::None; 480 // We only want simple or unordered-atomic stores. 481 if (!SI->isUnordered()) 482 return LegalStoreKind::None; 483 484 // Avoid merging nontemporal stores. 485 if (SI->getMetadata(LLVMContext::MD_nontemporal)) 486 return LegalStoreKind::None; 487 488 Value *StoredVal = SI->getValueOperand(); 489 Value *StorePtr = SI->getPointerOperand(); 490 491 // Don't convert stores of non-integral pointer types to memsets (which stores 492 // integers). 493 if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType())) 494 return LegalStoreKind::None; 495 496 // Reject stores that are so large that they overflow an unsigned. 497 // When storing out scalable vectors we bail out for now, since the code 498 // below currently only works for constant strides. 499 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 500 if (SizeInBits.isScalable() || (SizeInBits.getFixedSize() & 7) || 501 (SizeInBits.getFixedSize() >> 32) != 0) 502 return LegalStoreKind::None; 503 504 // See if the pointer expression is an AddRec like {base,+,1} on the current 505 // loop, which indicates a strided store. If we have something else, it's a 506 // random store we can't handle. 507 const SCEVAddRecExpr *StoreEv = 508 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 509 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 510 return LegalStoreKind::None; 511 512 // Check to see if we have a constant stride. 513 if (!isa<SCEVConstant>(StoreEv->getOperand(1))) 514 return LegalStoreKind::None; 515 516 // See if the store can be turned into a memset. 517 518 // If the stored value is a byte-wise value (like i32 -1), then it may be 519 // turned into a memset of i8 -1, assuming that all the consecutive bytes 520 // are stored. A store of i32 0x01020304 can never be turned into a memset, 521 // but it can be turned into memset_pattern if the target supports it. 522 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 523 524 // Note: memset and memset_pattern on unordered-atomic is yet not supported 525 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple(); 526 527 // If we're allowed to form a memset, and the stored value would be 528 // acceptable for memset, use it. 529 if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset && 530 // Verify that the stored value is loop invariant. If not, we can't 531 // promote the memset. 532 CurLoop->isLoopInvariant(SplatValue)) { 533 // It looks like we can use SplatValue. 534 return LegalStoreKind::Memset; 535 } 536 if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset && 537 // Don't create memset_pattern16s with address spaces. 538 StorePtr->getType()->getPointerAddressSpace() == 0 && 539 getMemSetPatternValue(StoredVal, DL)) { 540 // It looks like we can use PatternValue! 541 return LegalStoreKind::MemsetPattern; 542 } 543 544 // Otherwise, see if the store can be turned into a memcpy. 545 if (HasMemcpy && !DisableLIRP::Memcpy) { 546 // Check to see if the stride matches the size of the store. If so, then we 547 // know that every byte is touched in the loop. 548 APInt Stride = getStoreStride(StoreEv); 549 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 550 if (StoreSize != Stride && StoreSize != -Stride) 551 return LegalStoreKind::None; 552 553 // The store must be feeding a non-volatile load. 554 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 555 556 // Only allow non-volatile loads 557 if (!LI || LI->isVolatile()) 558 return LegalStoreKind::None; 559 // Only allow simple or unordered-atomic loads 560 if (!LI->isUnordered()) 561 return LegalStoreKind::None; 562 563 // See if the pointer expression is an AddRec like {base,+,1} on the current 564 // loop, which indicates a strided load. If we have something else, it's a 565 // random load we can't handle. 566 const SCEVAddRecExpr *LoadEv = 567 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 568 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 569 return LegalStoreKind::None; 570 571 // The store and load must share the same stride. 572 if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 573 return LegalStoreKind::None; 574 575 // Success. This store can be converted into a memcpy. 576 UnorderedAtomic = UnorderedAtomic || LI->isAtomic(); 577 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy 578 : LegalStoreKind::Memcpy; 579 } 580 // This store can't be transformed into a memset/memcpy. 581 return LegalStoreKind::None; 582 } 583 584 void LoopIdiomRecognize::collectStores(BasicBlock *BB) { 585 StoreRefsForMemset.clear(); 586 StoreRefsForMemsetPattern.clear(); 587 StoreRefsForMemcpy.clear(); 588 for (Instruction &I : *BB) { 589 StoreInst *SI = dyn_cast<StoreInst>(&I); 590 if (!SI) 591 continue; 592 593 // Make sure this is a strided store with a constant stride. 594 switch (isLegalStore(SI)) { 595 case LegalStoreKind::None: 596 // Nothing to do 597 break; 598 case LegalStoreKind::Memset: { 599 // Find the base pointer. 600 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 601 StoreRefsForMemset[Ptr].push_back(SI); 602 } break; 603 case LegalStoreKind::MemsetPattern: { 604 // Find the base pointer. 605 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 606 StoreRefsForMemsetPattern[Ptr].push_back(SI); 607 } break; 608 case LegalStoreKind::Memcpy: 609 case LegalStoreKind::UnorderedAtomicMemcpy: 610 StoreRefsForMemcpy.push_back(SI); 611 break; 612 default: 613 assert(false && "unhandled return value"); 614 break; 615 } 616 } 617 } 618 619 /// runOnLoopBlock - Process the specified block, which lives in a counted loop 620 /// with the specified backedge count. This block is known to be in the current 621 /// loop and not in any subloops. 622 bool LoopIdiomRecognize::runOnLoopBlock( 623 BasicBlock *BB, const SCEV *BECount, 624 SmallVectorImpl<BasicBlock *> &ExitBlocks) { 625 // We can only promote stores in this block if they are unconditionally 626 // executed in the loop. For a block to be unconditionally executed, it has 627 // to dominate all the exit blocks of the loop. Verify this now. 628 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 629 if (!DT->dominates(BB, ExitBlocks[i])) 630 return false; 631 632 bool MadeChange = false; 633 // Look for store instructions, which may be optimized to memset/memcpy. 634 collectStores(BB); 635 636 // Look for a single store or sets of stores with a common base, which can be 637 // optimized into a memset (memset_pattern). The latter most commonly happens 638 // with structs and handunrolled loops. 639 for (auto &SL : StoreRefsForMemset) 640 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes); 641 642 for (auto &SL : StoreRefsForMemsetPattern) 643 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No); 644 645 // Optimize the store into a memcpy, if it feeds an similarly strided load. 646 for (auto &SI : StoreRefsForMemcpy) 647 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); 648 649 MadeChange |= processLoopMemIntrinsic<MemCpyInst>( 650 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount); 651 MadeChange |= processLoopMemIntrinsic<MemSetInst>( 652 BB, &LoopIdiomRecognize::processLoopMemSet, BECount); 653 654 return MadeChange; 655 } 656 657 /// See if this store(s) can be promoted to a memset. 658 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, 659 const SCEV *BECount, ForMemset For) { 660 // Try to find consecutive stores that can be transformed into memsets. 661 SetVector<StoreInst *> Heads, Tails; 662 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; 663 664 // Do a quadratic search on all of the given stores and find 665 // all of the pairs of stores that follow each other. 666 SmallVector<unsigned, 16> IndexQueue; 667 for (unsigned i = 0, e = SL.size(); i < e; ++i) { 668 assert(SL[i]->isSimple() && "Expected only non-volatile stores."); 669 670 Value *FirstStoredVal = SL[i]->getValueOperand(); 671 Value *FirstStorePtr = SL[i]->getPointerOperand(); 672 const SCEVAddRecExpr *FirstStoreEv = 673 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); 674 APInt FirstStride = getStoreStride(FirstStoreEv); 675 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType()); 676 677 // See if we can optimize just this store in isolation. 678 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { 679 Heads.insert(SL[i]); 680 continue; 681 } 682 683 Value *FirstSplatValue = nullptr; 684 Constant *FirstPatternValue = nullptr; 685 686 if (For == ForMemset::Yes) 687 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL); 688 else 689 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); 690 691 assert((FirstSplatValue || FirstPatternValue) && 692 "Expected either splat value or pattern value."); 693 694 IndexQueue.clear(); 695 // If a store has multiple consecutive store candidates, search Stores 696 // array according to the sequence: from i+1 to e, then from i-1 to 0. 697 // This is because usually pairing with immediate succeeding or preceding 698 // candidate create the best chance to find memset opportunity. 699 unsigned j = 0; 700 for (j = i + 1; j < e; ++j) 701 IndexQueue.push_back(j); 702 for (j = i; j > 0; --j) 703 IndexQueue.push_back(j - 1); 704 705 for (auto &k : IndexQueue) { 706 assert(SL[k]->isSimple() && "Expected only non-volatile stores."); 707 Value *SecondStorePtr = SL[k]->getPointerOperand(); 708 const SCEVAddRecExpr *SecondStoreEv = 709 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); 710 APInt SecondStride = getStoreStride(SecondStoreEv); 711 712 if (FirstStride != SecondStride) 713 continue; 714 715 Value *SecondStoredVal = SL[k]->getValueOperand(); 716 Value *SecondSplatValue = nullptr; 717 Constant *SecondPatternValue = nullptr; 718 719 if (For == ForMemset::Yes) 720 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL); 721 else 722 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); 723 724 assert((SecondSplatValue || SecondPatternValue) && 725 "Expected either splat value or pattern value."); 726 727 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { 728 if (For == ForMemset::Yes) { 729 if (isa<UndefValue>(FirstSplatValue)) 730 FirstSplatValue = SecondSplatValue; 731 if (FirstSplatValue != SecondSplatValue) 732 continue; 733 } else { 734 if (isa<UndefValue>(FirstPatternValue)) 735 FirstPatternValue = SecondPatternValue; 736 if (FirstPatternValue != SecondPatternValue) 737 continue; 738 } 739 Tails.insert(SL[k]); 740 Heads.insert(SL[i]); 741 ConsecutiveChain[SL[i]] = SL[k]; 742 break; 743 } 744 } 745 } 746 747 // We may run into multiple chains that merge into a single chain. We mark the 748 // stores that we transformed so that we don't visit the same store twice. 749 SmallPtrSet<Value *, 16> TransformedStores; 750 bool Changed = false; 751 752 // For stores that start but don't end a link in the chain: 753 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); 754 it != e; ++it) { 755 if (Tails.count(*it)) 756 continue; 757 758 // We found a store instr that starts a chain. Now follow the chain and try 759 // to transform it. 760 SmallPtrSet<Instruction *, 8> AdjacentStores; 761 StoreInst *I = *it; 762 763 StoreInst *HeadStore = I; 764 unsigned StoreSize = 0; 765 766 // Collect the chain into a list. 767 while (Tails.count(I) || Heads.count(I)) { 768 if (TransformedStores.count(I)) 769 break; 770 AdjacentStores.insert(I); 771 772 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType()); 773 // Move to the next value in the chain. 774 I = ConsecutiveChain[I]; 775 } 776 777 Value *StoredVal = HeadStore->getValueOperand(); 778 Value *StorePtr = HeadStore->getPointerOperand(); 779 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 780 APInt Stride = getStoreStride(StoreEv); 781 782 // Check to see if the stride matches the size of the stores. If so, then 783 // we know that every byte is touched in the loop. 784 if (StoreSize != Stride && StoreSize != -Stride) 785 continue; 786 787 bool IsNegStride = StoreSize == -Stride; 788 789 Type *IntIdxTy = DL->getIndexType(StorePtr->getType()); 790 const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize); 791 if (processLoopStridedStore(StorePtr, StoreSizeSCEV, 792 MaybeAlign(HeadStore->getAlignment()), 793 StoredVal, HeadStore, AdjacentStores, StoreEv, 794 BECount, IsNegStride)) { 795 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); 796 Changed = true; 797 } 798 } 799 800 return Changed; 801 } 802 803 /// processLoopMemIntrinsic - Template function for calling different processor 804 /// functions based on mem instrinsic type. 805 template <typename MemInst> 806 bool LoopIdiomRecognize::processLoopMemIntrinsic( 807 BasicBlock *BB, 808 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *), 809 const SCEV *BECount) { 810 bool MadeChange = false; 811 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 812 Instruction *Inst = &*I++; 813 // Look for memory instructions, which may be optimized to a larger one. 814 if (MemInst *MI = dyn_cast<MemInst>(Inst)) { 815 WeakTrackingVH InstPtr(&*I); 816 if (!(this->*Processor)(MI, BECount)) 817 continue; 818 MadeChange = true; 819 820 // If processing the instruction invalidated our iterator, start over from 821 // the top of the block. 822 if (!InstPtr) 823 I = BB->begin(); 824 } 825 } 826 return MadeChange; 827 } 828 829 /// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy 830 bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI, 831 const SCEV *BECount) { 832 // We can only handle non-volatile memcpys with a constant size. 833 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength())) 834 return false; 835 836 // If we're not allowed to hack on memcpy, we fail. 837 if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy) 838 return false; 839 840 Value *Dest = MCI->getDest(); 841 Value *Source = MCI->getSource(); 842 if (!Dest || !Source) 843 return false; 844 845 // See if the load and store pointer expressions are AddRec like {base,+,1} on 846 // the current loop, which indicates a strided load and store. If we have 847 // something else, it's a random load or store we can't handle. 848 const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest)); 849 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 850 return false; 851 const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source)); 852 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 853 return false; 854 855 // Reject memcpys that are so large that they overflow an unsigned. 856 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue(); 857 if ((SizeInBytes >> 32) != 0) 858 return false; 859 860 // Check if the stride matches the size of the memcpy. If so, then we know 861 // that every byte is touched in the loop. 862 const SCEVConstant *ConstStoreStride = 863 dyn_cast<SCEVConstant>(StoreEv->getOperand(1)); 864 const SCEVConstant *ConstLoadStride = 865 dyn_cast<SCEVConstant>(LoadEv->getOperand(1)); 866 if (!ConstStoreStride || !ConstLoadStride) 867 return false; 868 869 APInt StoreStrideValue = ConstStoreStride->getAPInt(); 870 APInt LoadStrideValue = ConstLoadStride->getAPInt(); 871 // Huge stride value - give up 872 if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64) 873 return false; 874 875 if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) { 876 ORE.emit([&]() { 877 return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI) 878 << ore::NV("Inst", "memcpy") << " in " 879 << ore::NV("Function", MCI->getFunction()) 880 << " function will not be hoisted: " 881 << ore::NV("Reason", "memcpy size is not equal to stride"); 882 }); 883 return false; 884 } 885 886 int64_t StoreStrideInt = StoreStrideValue.getSExtValue(); 887 int64_t LoadStrideInt = LoadStrideValue.getSExtValue(); 888 // Check if the load stride matches the store stride. 889 if (StoreStrideInt != LoadStrideInt) 890 return false; 891 892 return processLoopStoreOfLoopLoad( 893 Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes), 894 MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI, StoreEv, LoadEv, 895 BECount); 896 } 897 898 /// processLoopMemSet - See if this memset can be promoted to a large memset. 899 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, 900 const SCEV *BECount) { 901 // We can only handle non-volatile memsets. 902 if (MSI->isVolatile()) 903 return false; 904 905 // If we're not allowed to hack on memset, we fail. 906 if (!HasMemset || DisableLIRP::Memset) 907 return false; 908 909 Value *Pointer = MSI->getDest(); 910 911 // See if the pointer expression is an AddRec like {base,+,1} on the current 912 // loop, which indicates a strided store. If we have something else, it's a 913 // random store we can't handle. 914 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); 915 if (!Ev || Ev->getLoop() != CurLoop) 916 return false; 917 if (!Ev->isAffine()) { 918 LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n"); 919 return false; 920 } 921 922 const SCEV *PointerStrideSCEV = Ev->getOperand(1); 923 const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength()); 924 if (!PointerStrideSCEV || !MemsetSizeSCEV) 925 return false; 926 927 bool IsNegStride = false; 928 const bool IsConstantSize = isa<ConstantInt>(MSI->getLength()); 929 930 if (IsConstantSize) { 931 // Memset size is constant. 932 // Check if the pointer stride matches the memset size. If so, then 933 // we know that every byte is touched in the loop. 934 LLVM_DEBUG(dbgs() << " memset size is constant\n"); 935 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 936 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); 937 if (!ConstStride) 938 return false; 939 940 APInt Stride = ConstStride->getAPInt(); 941 if (SizeInBytes != Stride && SizeInBytes != -Stride) 942 return false; 943 944 IsNegStride = SizeInBytes == -Stride; 945 } else { 946 // Memset size is non-constant. 947 // Check if the pointer stride matches the memset size. 948 // To be conservative, the pass would not promote pointers that aren't in 949 // address space zero. Also, the pass only handles memset length and stride 950 // that are invariant for the top level loop. 951 LLVM_DEBUG(dbgs() << " memset size is non-constant\n"); 952 if (Pointer->getType()->getPointerAddressSpace() != 0) { 953 LLVM_DEBUG(dbgs() << " pointer is not in address space zero, " 954 << "abort\n"); 955 return false; 956 } 957 if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) { 958 LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, " 959 << "abort\n"); 960 return false; 961 } 962 963 // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV 964 IsNegStride = PointerStrideSCEV->isNonConstantNegative(); 965 const SCEV *PositiveStrideSCEV = 966 IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV) 967 : PointerStrideSCEV; 968 LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n" 969 << " PositiveStrideSCEV: " << *PositiveStrideSCEV 970 << "\n"); 971 972 if (PositiveStrideSCEV != MemsetSizeSCEV) { 973 // TODO: folding can be done to the SCEVs 974 // The folding is to fold expressions that is covered by the loop guard 975 // at loop entry. After the folding, compare again and proceed 976 // optimization if equal. 977 LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n"); 978 return false; 979 } 980 } 981 982 // Verify that the memset value is loop invariant. If not, we can't promote 983 // the memset. 984 Value *SplatValue = MSI->getValue(); 985 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) 986 return false; 987 988 SmallPtrSet<Instruction *, 1> MSIs; 989 MSIs.insert(MSI); 990 return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()), 991 MaybeAlign(MSI->getDestAlignment()), 992 SplatValue, MSI, MSIs, Ev, BECount, 993 IsNegStride, /*IsLoopMemset=*/true); 994 } 995 996 /// mayLoopAccessLocation - Return true if the specified loop might access the 997 /// specified pointer location, which is a loop-strided access. The 'Access' 998 /// argument specifies what the verboten forms of access are (read or write). 999 static bool 1000 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 1001 const SCEV *BECount, const SCEV *StoreSizeSCEV, 1002 AliasAnalysis &AA, 1003 SmallPtrSetImpl<Instruction *> &IgnoredInsts) { 1004 // Get the location that may be stored across the loop. Since the access is 1005 // strided positively through memory, we say that the modified location starts 1006 // at the pointer and has infinite size. 1007 LocationSize AccessSize = LocationSize::afterPointer(); 1008 1009 // If the loop iterates a fixed number of times, we can refine the access size 1010 // to be exactly the size of the memset, which is (BECount+1)*StoreSize 1011 const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount); 1012 const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV); 1013 if (BECst && ConstSize) 1014 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * 1015 ConstSize->getValue()->getZExtValue()); 1016 1017 // TODO: For this to be really effective, we have to dive into the pointer 1018 // operand in the store. Store to &A[i] of 100 will always return may alias 1019 // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 1020 // which will then no-alias a store to &A[100]. 1021 MemoryLocation StoreLoc(Ptr, AccessSize); 1022 1023 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; 1024 ++BI) 1025 for (Instruction &I : **BI) 1026 if (IgnoredInsts.count(&I) == 0 && 1027 isModOrRefSet( 1028 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access))) 1029 return true; 1030 return false; 1031 } 1032 1033 // If we have a negative stride, Start refers to the end of the memory location 1034 // we're trying to memset. Therefore, we need to recompute the base pointer, 1035 // which is just Start - BECount*Size. 1036 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, 1037 Type *IntPtr, const SCEV *StoreSizeSCEV, 1038 ScalarEvolution *SE) { 1039 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); 1040 if (!StoreSizeSCEV->isOne()) { 1041 // index = back edge count * store size 1042 Index = SE->getMulExpr(Index, 1043 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr), 1044 SCEV::FlagNUW); 1045 } 1046 // base pointer = start - index * store size 1047 return SE->getMinusSCEV(Start, Index); 1048 } 1049 1050 /// Compute trip count from the backedge taken count. 1051 static const SCEV *getTripCount(const SCEV *BECount, Type *IntPtr, 1052 Loop *CurLoop, const DataLayout *DL, 1053 ScalarEvolution *SE) { 1054 const SCEV *TripCountS = nullptr; 1055 // The # stored bytes is (BECount+1). Expand the trip count out to 1056 // pointer size if it isn't already. 1057 // 1058 // If we're going to need to zero extend the BE count, check if we can add 1059 // one to it prior to zero extending without overflow. Provided this is safe, 1060 // it allows better simplification of the +1. 1061 if (DL->getTypeSizeInBits(BECount->getType()) < 1062 DL->getTypeSizeInBits(IntPtr) && 1063 SE->isLoopEntryGuardedByCond( 1064 CurLoop, ICmpInst::ICMP_NE, BECount, 1065 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) { 1066 TripCountS = SE->getZeroExtendExpr( 1067 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW), 1068 IntPtr); 1069 } else { 1070 TripCountS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr), 1071 SE->getOne(IntPtr), SCEV::FlagNUW); 1072 } 1073 1074 return TripCountS; 1075 } 1076 1077 /// Compute the number of bytes as a SCEV from the backedge taken count. 1078 /// 1079 /// This also maps the SCEV into the provided type and tries to handle the 1080 /// computation in a way that will fold cleanly. 1081 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr, 1082 const SCEV *StoreSizeSCEV, Loop *CurLoop, 1083 const DataLayout *DL, ScalarEvolution *SE) { 1084 const SCEV *TripCountSCEV = getTripCount(BECount, IntPtr, CurLoop, DL, SE); 1085 1086 return SE->getMulExpr(TripCountSCEV, 1087 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr), 1088 SCEV::FlagNUW); 1089 } 1090 1091 /// processLoopStridedStore - We see a strided store of some value. If we can 1092 /// transform this into a memset or memset_pattern in the loop preheader, do so. 1093 bool LoopIdiomRecognize::processLoopStridedStore( 1094 Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment, 1095 Value *StoredVal, Instruction *TheStore, 1096 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, 1097 const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) { 1098 Value *SplatValue = isBytewiseValue(StoredVal, *DL); 1099 Constant *PatternValue = nullptr; 1100 1101 if (!SplatValue) 1102 PatternValue = getMemSetPatternValue(StoredVal, DL); 1103 1104 assert((SplatValue || PatternValue) && 1105 "Expected either splat value or pattern value."); 1106 1107 // The trip count of the loop and the base pointer of the addrec SCEV is 1108 // guaranteed to be loop invariant, which means that it should dominate the 1109 // header. This allows us to insert code for it in the preheader. 1110 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); 1111 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1112 IRBuilder<> Builder(Preheader->getTerminator()); 1113 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1114 SCEVExpanderCleaner ExpCleaner(Expander, *DT); 1115 1116 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); 1117 Type *IntIdxTy = DL->getIndexType(DestPtr->getType()); 1118 1119 bool Changed = false; 1120 const SCEV *Start = Ev->getStart(); 1121 // Handle negative strided loops. 1122 if (IsNegStride) 1123 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE); 1124 1125 // TODO: ideally we should still be able to generate memset if SCEV expander 1126 // is taught to generate the dependencies at the latest point. 1127 if (!isSafeToExpand(Start, *SE)) 1128 return Changed; 1129 1130 // Okay, we have a strided store "p[i]" of a splattable value. We can turn 1131 // this into a memset in the loop preheader now if we want. However, this 1132 // would be unsafe to do if there is anything else in the loop that may read 1133 // or write to the aliased location. Check for any overlap by generating the 1134 // base pointer and checking the region. 1135 Value *BasePtr = 1136 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); 1137 1138 // From here on out, conservatively report to the pass manager that we've 1139 // changed the IR, even if we later clean up these added instructions. There 1140 // may be structural differences e.g. in the order of use lists not accounted 1141 // for in just a textual dump of the IR. This is written as a variable, even 1142 // though statically all the places this dominates could be replaced with 1143 // 'true', with the hope that anyone trying to be clever / "more precise" with 1144 // the return value will read this comment, and leave them alone. 1145 Changed = true; 1146 1147 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1148 StoreSizeSCEV, *AA, Stores)) 1149 return Changed; 1150 1151 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) 1152 return Changed; 1153 1154 // Okay, everything looks good, insert the memset. 1155 1156 const SCEV *NumBytesS = 1157 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE); 1158 1159 // TODO: ideally we should still be able to generate memset if SCEV expander 1160 // is taught to generate the dependencies at the latest point. 1161 if (!isSafeToExpand(NumBytesS, *SE)) 1162 return Changed; 1163 1164 Value *NumBytes = 1165 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1166 1167 CallInst *NewCall; 1168 if (SplatValue) { 1169 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, 1170 MaybeAlign(StoreAlignment)); 1171 } else { 1172 // Everything is emitted in default address space 1173 Type *Int8PtrTy = DestInt8PtrTy; 1174 1175 Module *M = TheStore->getModule(); 1176 StringRef FuncName = "memset_pattern16"; 1177 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(), 1178 Int8PtrTy, Int8PtrTy, IntIdxTy); 1179 inferLibFuncAttributes(M, FuncName, *TLI); 1180 1181 // Otherwise we should form a memset_pattern16. PatternValue is known to be 1182 // an constant array of 16-bytes. Plop the value into a mergable global. 1183 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, 1184 GlobalValue::PrivateLinkage, 1185 PatternValue, ".memset_pattern"); 1186 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. 1187 GV->setAlignment(Align(16)); 1188 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); 1189 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); 1190 } 1191 NewCall->setDebugLoc(TheStore->getDebugLoc()); 1192 1193 if (MSSAU) { 1194 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1195 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1196 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1197 } 1198 1199 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" 1200 << " from store to: " << *Ev << " at: " << *TheStore 1201 << "\n"); 1202 1203 ORE.emit([&]() { 1204 OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore", 1205 NewCall->getDebugLoc(), Preheader); 1206 R << "Transformed loop-strided store in " 1207 << ore::NV("Function", TheStore->getFunction()) 1208 << " function into a call to " 1209 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1210 << "() intrinsic"; 1211 if (!Stores.empty()) 1212 R << ore::setExtraArgs(); 1213 for (auto *I : Stores) { 1214 R << ore::NV("FromBlock", I->getParent()->getName()) 1215 << ore::NV("ToBlock", Preheader->getName()); 1216 } 1217 return R; 1218 }); 1219 1220 // Okay, the memset has been formed. Zap the original store and anything that 1221 // feeds into it. 1222 for (auto *I : Stores) { 1223 if (MSSAU) 1224 MSSAU->removeMemoryAccess(I, true); 1225 deleteDeadInstruction(I); 1226 } 1227 if (MSSAU && VerifyMemorySSA) 1228 MSSAU->getMemorySSA()->verifyMemorySSA(); 1229 ++NumMemSet; 1230 ExpCleaner.markResultUsed(); 1231 return true; 1232 } 1233 1234 /// If the stored value is a strided load in the same loop with the same stride 1235 /// this may be transformable into a memcpy. This kicks in for stuff like 1236 /// for (i) A[i] = B[i]; 1237 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, 1238 const SCEV *BECount) { 1239 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores."); 1240 1241 Value *StorePtr = SI->getPointerOperand(); 1242 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 1243 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 1244 1245 // The store must be feeding a non-volatile load. 1246 LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); 1247 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads."); 1248 1249 // See if the pointer expression is an AddRec like {base,+,1} on the current 1250 // loop, which indicates a strided load. If we have something else, it's a 1251 // random load we can't handle. 1252 Value *LoadPtr = LI->getPointerOperand(); 1253 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr)); 1254 1255 const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize); 1256 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV, 1257 SI->getAlign(), LI->getAlign(), SI, LI, 1258 StoreEv, LoadEv, BECount); 1259 } 1260 1261 class MemmoveVerifier { 1262 public: 1263 explicit MemmoveVerifier(const Value &LoadBasePtr, const Value &StoreBasePtr, 1264 const DataLayout &DL) 1265 : DL(DL), LoadOff(0), StoreOff(0), 1266 BP1(llvm::GetPointerBaseWithConstantOffset( 1267 LoadBasePtr.stripPointerCasts(), LoadOff, DL)), 1268 BP2(llvm::GetPointerBaseWithConstantOffset( 1269 StoreBasePtr.stripPointerCasts(), StoreOff, DL)), 1270 IsSameObject(BP1 == BP2) {} 1271 1272 bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride, 1273 const Instruction &TheLoad, 1274 bool IsMemCpy) const { 1275 if (IsMemCpy) { 1276 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr 1277 // for negative stride. 1278 if ((!IsNegStride && LoadOff <= StoreOff) || 1279 (IsNegStride && LoadOff >= StoreOff)) 1280 return false; 1281 } else { 1282 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr 1283 // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr. 1284 int64_t LoadSize = 1285 DL.getTypeSizeInBits(TheLoad.getType()).getFixedSize() / 8; 1286 if (BP1 != BP2 || LoadSize != int64_t(StoreSize)) 1287 return false; 1288 if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) || 1289 (IsNegStride && LoadOff + LoadSize > StoreOff)) 1290 return false; 1291 } 1292 return true; 1293 } 1294 1295 private: 1296 const DataLayout &DL; 1297 int64_t LoadOff; 1298 int64_t StoreOff; 1299 const Value *BP1; 1300 const Value *BP2; 1301 1302 public: 1303 const bool IsSameObject; 1304 }; 1305 1306 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad( 1307 Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV, 1308 MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore, 1309 Instruction *TheLoad, const SCEVAddRecExpr *StoreEv, 1310 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) { 1311 1312 // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to 1313 // conservatively bail here, since otherwise we may have to transform 1314 // llvm.memcpy.inline into llvm.memcpy which is illegal. 1315 if (isa<MemCpyInlineInst>(TheStore)) 1316 return false; 1317 1318 // The trip count of the loop and the base pointer of the addrec SCEV is 1319 // guaranteed to be loop invariant, which means that it should dominate the 1320 // header. This allows us to insert code for it in the preheader. 1321 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 1322 IRBuilder<> Builder(Preheader->getTerminator()); 1323 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 1324 1325 SCEVExpanderCleaner ExpCleaner(Expander, *DT); 1326 1327 bool Changed = false; 1328 const SCEV *StrStart = StoreEv->getStart(); 1329 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace(); 1330 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS)); 1331 1332 APInt Stride = getStoreStride(StoreEv); 1333 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV); 1334 1335 // TODO: Deal with non-constant size; Currently expect constant store size 1336 assert(ConstStoreSize && "store size is expected to be a constant"); 1337 1338 int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue(); 1339 bool IsNegStride = StoreSize == -Stride; 1340 1341 // Handle negative strided loops. 1342 if (IsNegStride) 1343 StrStart = 1344 getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE); 1345 1346 // Okay, we have a strided store "p[i]" of a loaded value. We can turn 1347 // this into a memcpy in the loop preheader now if we want. However, this 1348 // would be unsafe to do if there is anything else in the loop that may read 1349 // or write the memory region we're storing to. This includes the load that 1350 // feeds the stores. Check for an alias by generating the base address and 1351 // checking everything. 1352 Value *StoreBasePtr = Expander.expandCodeFor( 1353 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); 1354 1355 // From here on out, conservatively report to the pass manager that we've 1356 // changed the IR, even if we later clean up these added instructions. There 1357 // may be structural differences e.g. in the order of use lists not accounted 1358 // for in just a textual dump of the IR. This is written as a variable, even 1359 // though statically all the places this dominates could be replaced with 1360 // 'true', with the hope that anyone trying to be clever / "more precise" with 1361 // the return value will read this comment, and leave them alone. 1362 Changed = true; 1363 1364 SmallPtrSet<Instruction *, 2> IgnoredInsts; 1365 IgnoredInsts.insert(TheStore); 1366 1367 bool IsMemCpy = isa<MemCpyInst>(TheStore); 1368 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store"; 1369 1370 bool LoopAccessStore = 1371 mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, 1372 StoreSizeSCEV, *AA, IgnoredInsts); 1373 if (LoopAccessStore) { 1374 // For memmove case it's not enough to guarantee that loop doesn't access 1375 // TheStore and TheLoad. Additionally we need to make sure that TheStore is 1376 // the only user of TheLoad. 1377 if (!TheLoad->hasOneUse()) 1378 return Changed; 1379 IgnoredInsts.insert(TheLoad); 1380 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, 1381 BECount, StoreSizeSCEV, *AA, IgnoredInsts)) { 1382 ORE.emit([&]() { 1383 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore", 1384 TheStore) 1385 << ore::NV("Inst", InstRemark) << " in " 1386 << ore::NV("Function", TheStore->getFunction()) 1387 << " function will not be hoisted: " 1388 << ore::NV("Reason", "The loop may access store location"); 1389 }); 1390 return Changed; 1391 } 1392 IgnoredInsts.erase(TheLoad); 1393 } 1394 1395 const SCEV *LdStart = LoadEv->getStart(); 1396 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace(); 1397 1398 // Handle negative strided loops. 1399 if (IsNegStride) 1400 LdStart = 1401 getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE); 1402 1403 // For a memcpy, we have to make sure that the input array is not being 1404 // mutated by the loop. 1405 Value *LoadBasePtr = Expander.expandCodeFor( 1406 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); 1407 1408 // If the store is a memcpy instruction, we must check if it will write to 1409 // the load memory locations. So remove it from the ignored stores. 1410 if (IsMemCpy) 1411 IgnoredInsts.erase(TheStore); 1412 MemmoveVerifier Verifier(*LoadBasePtr, *StoreBasePtr, *DL); 1413 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, 1414 StoreSizeSCEV, *AA, IgnoredInsts)) { 1415 if (!IsMemCpy) { 1416 ORE.emit([&]() { 1417 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", 1418 TheLoad) 1419 << ore::NV("Inst", InstRemark) << " in " 1420 << ore::NV("Function", TheStore->getFunction()) 1421 << " function will not be hoisted: " 1422 << ore::NV("Reason", "The loop may access load location"); 1423 }); 1424 return Changed; 1425 } 1426 // At this point loop may access load only for memcpy in same underlying 1427 // object. If that's not the case bail out. 1428 if (!Verifier.IsSameObject) 1429 return Changed; 1430 } 1431 1432 bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore; 1433 if (UseMemMove) 1434 if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad, 1435 IsMemCpy)) 1436 return Changed; 1437 1438 if (avoidLIRForMultiBlockLoop()) 1439 return Changed; 1440 1441 // Okay, everything is safe, we can transform this! 1442 1443 const SCEV *NumBytesS = 1444 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE); 1445 1446 Value *NumBytes = 1447 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator()); 1448 1449 CallInst *NewCall = nullptr; 1450 // Check whether to generate an unordered atomic memcpy: 1451 // If the load or store are atomic, then they must necessarily be unordered 1452 // by previous checks. 1453 if (!TheStore->isAtomic() && !TheLoad->isAtomic()) { 1454 if (UseMemMove) 1455 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr, 1456 LoadAlign, NumBytes); 1457 else 1458 NewCall = Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, 1459 LoadAlign, NumBytes); 1460 } else { 1461 // For now don't support unordered atomic memmove. 1462 if (UseMemMove) 1463 return Changed; 1464 // We cannot allow unaligned ops for unordered load/store, so reject 1465 // anything where the alignment isn't at least the element size. 1466 assert((StoreAlign.hasValue() && LoadAlign.hasValue()) && 1467 "Expect unordered load/store to have align."); 1468 if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize) 1469 return Changed; 1470 1471 // If the element.atomic memcpy is not lowered into explicit 1472 // loads/stores later, then it will be lowered into an element-size 1473 // specific lib call. If the lib call doesn't exist for our store size, then 1474 // we shouldn't generate the memcpy. 1475 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize()) 1476 return Changed; 1477 1478 // Create the call. 1479 // Note that unordered atomic loads/stores are *required* by the spec to 1480 // have an alignment but non-atomic loads/stores may not. 1481 NewCall = Builder.CreateElementUnorderedAtomicMemCpy( 1482 StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(), 1483 NumBytes, StoreSize); 1484 } 1485 NewCall->setDebugLoc(TheStore->getDebugLoc()); 1486 1487 if (MSSAU) { 1488 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( 1489 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator); 1490 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true); 1491 } 1492 1493 LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n" 1494 << " from load ptr=" << *LoadEv << " at: " << *TheLoad 1495 << "\n" 1496 << " from store ptr=" << *StoreEv << " at: " << *TheStore 1497 << "\n"); 1498 1499 ORE.emit([&]() { 1500 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad", 1501 NewCall->getDebugLoc(), Preheader) 1502 << "Formed a call to " 1503 << ore::NV("NewFunction", NewCall->getCalledFunction()) 1504 << "() intrinsic from " << ore::NV("Inst", InstRemark) 1505 << " instruction in " << ore::NV("Function", TheStore->getFunction()) 1506 << " function" 1507 << ore::setExtraArgs() 1508 << ore::NV("FromBlock", TheStore->getParent()->getName()) 1509 << ore::NV("ToBlock", Preheader->getName()); 1510 }); 1511 1512 // Okay, a new call to memcpy/memmove has been formed. Zap the original store 1513 // and anything that feeds into it. 1514 if (MSSAU) 1515 MSSAU->removeMemoryAccess(TheStore, true); 1516 deleteDeadInstruction(TheStore); 1517 if (MSSAU && VerifyMemorySSA) 1518 MSSAU->getMemorySSA()->verifyMemorySSA(); 1519 if (UseMemMove) 1520 ++NumMemMove; 1521 else 1522 ++NumMemCpy; 1523 ExpCleaner.markResultUsed(); 1524 return true; 1525 } 1526 1527 // When compiling for codesize we avoid idiom recognition for a multi-block loop 1528 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. 1529 // 1530 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, 1531 bool IsLoopMemset) { 1532 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { 1533 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) { 1534 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() 1535 << " : LIR " << (IsMemset ? "Memset" : "Memcpy") 1536 << " avoided: multi-block top-level loop\n"); 1537 return true; 1538 } 1539 } 1540 1541 return false; 1542 } 1543 1544 bool LoopIdiomRecognize::runOnNoncountableLoop() { 1545 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" 1546 << CurLoop->getHeader()->getParent()->getName() 1547 << "] Noncountable Loop %" 1548 << CurLoop->getHeader()->getName() << "\n"); 1549 1550 return recognizePopcount() || recognizeAndInsertFFS() || 1551 recognizeShiftUntilBitTest() || recognizeShiftUntilZero(); 1552 } 1553 1554 /// Check if the given conditional branch is based on the comparison between 1555 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is 1556 /// true), the control yields to the loop entry. If the branch matches the 1557 /// behavior, the variable involved in the comparison is returned. This function 1558 /// will be called to see if the precondition and postcondition of the loop are 1559 /// in desirable form. 1560 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry, 1561 bool JmpOnZero = false) { 1562 if (!BI || !BI->isConditional()) 1563 return nullptr; 1564 1565 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1566 if (!Cond) 1567 return nullptr; 1568 1569 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); 1570 if (!CmpZero || !CmpZero->isZero()) 1571 return nullptr; 1572 1573 BasicBlock *TrueSucc = BI->getSuccessor(0); 1574 BasicBlock *FalseSucc = BI->getSuccessor(1); 1575 if (JmpOnZero) 1576 std::swap(TrueSucc, FalseSucc); 1577 1578 ICmpInst::Predicate Pred = Cond->getPredicate(); 1579 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) || 1580 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry)) 1581 return Cond->getOperand(0); 1582 1583 return nullptr; 1584 } 1585 1586 // Check if the recurrence variable `VarX` is in the right form to create 1587 // the idiom. Returns the value coerced to a PHINode if so. 1588 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX, 1589 BasicBlock *LoopEntry) { 1590 auto *PhiX = dyn_cast<PHINode>(VarX); 1591 if (PhiX && PhiX->getParent() == LoopEntry && 1592 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX)) 1593 return PhiX; 1594 return nullptr; 1595 } 1596 1597 /// Return true iff the idiom is detected in the loop. 1598 /// 1599 /// Additionally: 1600 /// 1) \p CntInst is set to the instruction counting the population bit. 1601 /// 2) \p CntPhi is set to the corresponding phi node. 1602 /// 3) \p Var is set to the value whose population bits are being counted. 1603 /// 1604 /// The core idiom we are trying to detect is: 1605 /// \code 1606 /// if (x0 != 0) 1607 /// goto loop-exit // the precondition of the loop 1608 /// cnt0 = init-val; 1609 /// do { 1610 /// x1 = phi (x0, x2); 1611 /// cnt1 = phi(cnt0, cnt2); 1612 /// 1613 /// cnt2 = cnt1 + 1; 1614 /// ... 1615 /// x2 = x1 & (x1 - 1); 1616 /// ... 1617 /// } while(x != 0); 1618 /// 1619 /// loop-exit: 1620 /// \endcode 1621 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, 1622 Instruction *&CntInst, PHINode *&CntPhi, 1623 Value *&Var) { 1624 // step 1: Check to see if the look-back branch match this pattern: 1625 // "if (a!=0) goto loop-entry". 1626 BasicBlock *LoopEntry; 1627 Instruction *DefX2, *CountInst; 1628 Value *VarX1, *VarX0; 1629 PHINode *PhiX, *CountPhi; 1630 1631 DefX2 = CountInst = nullptr; 1632 VarX1 = VarX0 = nullptr; 1633 PhiX = CountPhi = nullptr; 1634 LoopEntry = *(CurLoop->block_begin()); 1635 1636 // step 1: Check if the loop-back branch is in desirable form. 1637 { 1638 if (Value *T = matchCondition( 1639 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1640 DefX2 = dyn_cast<Instruction>(T); 1641 else 1642 return false; 1643 } 1644 1645 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" 1646 { 1647 if (!DefX2 || DefX2->getOpcode() != Instruction::And) 1648 return false; 1649 1650 BinaryOperator *SubOneOp; 1651 1652 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) 1653 VarX1 = DefX2->getOperand(1); 1654 else { 1655 VarX1 = DefX2->getOperand(0); 1656 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); 1657 } 1658 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1) 1659 return false; 1660 1661 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1)); 1662 if (!Dec || 1663 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) || 1664 (SubOneOp->getOpcode() == Instruction::Add && 1665 Dec->isMinusOne()))) { 1666 return false; 1667 } 1668 } 1669 1670 // step 3: Check the recurrence of variable X 1671 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry); 1672 if (!PhiX) 1673 return false; 1674 1675 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 1676 { 1677 CountInst = nullptr; 1678 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1679 IterE = LoopEntry->end(); 1680 Iter != IterE; Iter++) { 1681 Instruction *Inst = &*Iter; 1682 if (Inst->getOpcode() != Instruction::Add) 1683 continue; 1684 1685 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1686 if (!Inc || !Inc->isOne()) 1687 continue; 1688 1689 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1690 if (!Phi) 1691 continue; 1692 1693 // Check if the result of the instruction is live of the loop. 1694 bool LiveOutLoop = false; 1695 for (User *U : Inst->users()) { 1696 if ((cast<Instruction>(U))->getParent() != LoopEntry) { 1697 LiveOutLoop = true; 1698 break; 1699 } 1700 } 1701 1702 if (LiveOutLoop) { 1703 CountInst = Inst; 1704 CountPhi = Phi; 1705 break; 1706 } 1707 } 1708 1709 if (!CountInst) 1710 return false; 1711 } 1712 1713 // step 5: check if the precondition is in this form: 1714 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" 1715 { 1716 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1717 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); 1718 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) 1719 return false; 1720 1721 CntInst = CountInst; 1722 CntPhi = CountPhi; 1723 Var = T; 1724 } 1725 1726 return true; 1727 } 1728 1729 /// Return true if the idiom is detected in the loop. 1730 /// 1731 /// Additionally: 1732 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) 1733 /// or nullptr if there is no such. 1734 /// 2) \p CntPhi is set to the corresponding phi node 1735 /// or nullptr if there is no such. 1736 /// 3) \p Var is set to the value whose CTLZ could be used. 1737 /// 4) \p DefX is set to the instruction calculating Loop exit condition. 1738 /// 1739 /// The core idiom we are trying to detect is: 1740 /// \code 1741 /// if (x0 == 0) 1742 /// goto loop-exit // the precondition of the loop 1743 /// cnt0 = init-val; 1744 /// do { 1745 /// x = phi (x0, x.next); //PhiX 1746 /// cnt = phi(cnt0, cnt.next); 1747 /// 1748 /// cnt.next = cnt + 1; 1749 /// ... 1750 /// x.next = x >> 1; // DefX 1751 /// ... 1752 /// } while(x.next != 0); 1753 /// 1754 /// loop-exit: 1755 /// \endcode 1756 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, 1757 Intrinsic::ID &IntrinID, Value *&InitX, 1758 Instruction *&CntInst, PHINode *&CntPhi, 1759 Instruction *&DefX) { 1760 BasicBlock *LoopEntry; 1761 Value *VarX = nullptr; 1762 1763 DefX = nullptr; 1764 CntInst = nullptr; 1765 CntPhi = nullptr; 1766 LoopEntry = *(CurLoop->block_begin()); 1767 1768 // step 1: Check if the loop-back branch is in desirable form. 1769 if (Value *T = matchCondition( 1770 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) 1771 DefX = dyn_cast<Instruction>(T); 1772 else 1773 return false; 1774 1775 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1" 1776 if (!DefX || !DefX->isShift()) 1777 return false; 1778 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz : 1779 Intrinsic::ctlz; 1780 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)); 1781 if (!Shft || !Shft->isOne()) 1782 return false; 1783 VarX = DefX->getOperand(0); 1784 1785 // step 3: Check the recurrence of variable X 1786 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry); 1787 if (!PhiX) 1788 return false; 1789 1790 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader()); 1791 1792 // Make sure the initial value can't be negative otherwise the ashr in the 1793 // loop might never reach zero which would make the loop infinite. 1794 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL)) 1795 return false; 1796 1797 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 1798 // or cnt.next = cnt + -1. 1799 // TODO: We can skip the step. If loop trip count is known (CTLZ), 1800 // then all uses of "cnt.next" could be optimized to the trip count 1801 // plus "cnt0". Currently it is not optimized. 1802 // This step could be used to detect POPCNT instruction: 1803 // cnt.next = cnt + (x.next & 1) 1804 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), 1805 IterE = LoopEntry->end(); 1806 Iter != IterE; Iter++) { 1807 Instruction *Inst = &*Iter; 1808 if (Inst->getOpcode() != Instruction::Add) 1809 continue; 1810 1811 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); 1812 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne())) 1813 continue; 1814 1815 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); 1816 if (!Phi) 1817 continue; 1818 1819 CntInst = Inst; 1820 CntPhi = Phi; 1821 break; 1822 } 1823 if (!CntInst) 1824 return false; 1825 1826 return true; 1827 } 1828 1829 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop 1830 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new 1831 /// trip count returns true; otherwise, returns false. 1832 bool LoopIdiomRecognize::recognizeAndInsertFFS() { 1833 // Give up if the loop has multiple blocks or multiple backedges. 1834 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1835 return false; 1836 1837 Intrinsic::ID IntrinID; 1838 Value *InitX; 1839 Instruction *DefX = nullptr; 1840 PHINode *CntPhi = nullptr; 1841 Instruction *CntInst = nullptr; 1842 // Help decide if transformation is profitable. For ShiftUntilZero idiom, 1843 // this is always 6. 1844 size_t IdiomCanonicalSize = 6; 1845 1846 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, 1847 CntInst, CntPhi, DefX)) 1848 return false; 1849 1850 bool IsCntPhiUsedOutsideLoop = false; 1851 for (User *U : CntPhi->users()) 1852 if (!CurLoop->contains(cast<Instruction>(U))) { 1853 IsCntPhiUsedOutsideLoop = true; 1854 break; 1855 } 1856 bool IsCntInstUsedOutsideLoop = false; 1857 for (User *U : CntInst->users()) 1858 if (!CurLoop->contains(cast<Instruction>(U))) { 1859 IsCntInstUsedOutsideLoop = true; 1860 break; 1861 } 1862 // If both CntInst and CntPhi are used outside the loop the profitability 1863 // is questionable. 1864 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) 1865 return false; 1866 1867 // For some CPUs result of CTLZ(X) intrinsic is undefined 1868 // when X is 0. If we can not guarantee X != 0, we need to check this 1869 // when expand. 1870 bool ZeroCheck = false; 1871 // It is safe to assume Preheader exist as it was checked in 1872 // parent function RunOnLoop. 1873 BasicBlock *PH = CurLoop->getLoopPreheader(); 1874 1875 // If we are using the count instruction outside the loop, make sure we 1876 // have a zero check as a precondition. Without the check the loop would run 1877 // one iteration for before any check of the input value. This means 0 and 1 1878 // would have identical behavior in the original loop and thus 1879 if (!IsCntPhiUsedOutsideLoop) { 1880 auto *PreCondBB = PH->getSinglePredecessor(); 1881 if (!PreCondBB) 1882 return false; 1883 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1884 if (!PreCondBI) 1885 return false; 1886 if (matchCondition(PreCondBI, PH) != InitX) 1887 return false; 1888 ZeroCheck = true; 1889 } 1890 1891 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always 1892 // profitable if we delete the loop. 1893 1894 // the loop has only 6 instructions: 1895 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] 1896 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] 1897 // %shr = ashr %n.addr.0, 1 1898 // %tobool = icmp eq %shr, 0 1899 // %inc = add nsw %i.0, 1 1900 // br i1 %tobool 1901 1902 const Value *Args[] = {InitX, 1903 ConstantInt::getBool(InitX->getContext(), ZeroCheck)}; 1904 1905 // @llvm.dbg doesn't count as they have no semantic effect. 1906 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug(); 1907 uint32_t HeaderSize = 1908 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end()); 1909 1910 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args); 1911 InstructionCost Cost = 1912 TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency); 1913 if (HeaderSize != IdiomCanonicalSize && 1914 Cost > TargetTransformInfo::TCC_Basic) 1915 return false; 1916 1917 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX, 1918 DefX->getDebugLoc(), ZeroCheck, 1919 IsCntPhiUsedOutsideLoop); 1920 return true; 1921 } 1922 1923 /// Recognizes a population count idiom in a non-countable loop. 1924 /// 1925 /// If detected, transforms the relevant code to issue the popcount intrinsic 1926 /// function call, and returns true; otherwise, returns false. 1927 bool LoopIdiomRecognize::recognizePopcount() { 1928 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) 1929 return false; 1930 1931 // Counting population are usually conducted by few arithmetic instructions. 1932 // Such instructions can be easily "absorbed" by vacant slots in a 1933 // non-compact loop. Therefore, recognizing popcount idiom only makes sense 1934 // in a compact loop. 1935 1936 // Give up if the loop has multiple blocks or multiple backedges. 1937 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) 1938 return false; 1939 1940 BasicBlock *LoopBody = *(CurLoop->block_begin()); 1941 if (LoopBody->size() >= 20) { 1942 // The loop is too big, bail out. 1943 return false; 1944 } 1945 1946 // It should have a preheader containing nothing but an unconditional branch. 1947 BasicBlock *PH = CurLoop->getLoopPreheader(); 1948 if (!PH || &PH->front() != PH->getTerminator()) 1949 return false; 1950 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); 1951 if (!EntryBI || EntryBI->isConditional()) 1952 return false; 1953 1954 // It should have a precondition block where the generated popcount intrinsic 1955 // function can be inserted. 1956 auto *PreCondBB = PH->getSinglePredecessor(); 1957 if (!PreCondBB) 1958 return false; 1959 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); 1960 if (!PreCondBI || PreCondBI->isUnconditional()) 1961 return false; 1962 1963 Instruction *CntInst; 1964 PHINode *CntPhi; 1965 Value *Val; 1966 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) 1967 return false; 1968 1969 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); 1970 return true; 1971 } 1972 1973 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1974 const DebugLoc &DL) { 1975 Value *Ops[] = {Val}; 1976 Type *Tys[] = {Val->getType()}; 1977 1978 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1979 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); 1980 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1981 CI->setDebugLoc(DL); 1982 1983 return CI; 1984 } 1985 1986 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, 1987 const DebugLoc &DL, bool ZeroCheck, 1988 Intrinsic::ID IID) { 1989 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)}; 1990 Type *Tys[] = {Val->getType()}; 1991 1992 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); 1993 Function *Func = Intrinsic::getDeclaration(M, IID, Tys); 1994 CallInst *CI = IRBuilder.CreateCall(Func, Ops); 1995 CI->setDebugLoc(DL); 1996 1997 return CI; 1998 } 1999 2000 /// Transform the following loop (Using CTLZ, CTTZ is similar): 2001 /// loop: 2002 /// CntPhi = PHI [Cnt0, CntInst] 2003 /// PhiX = PHI [InitX, DefX] 2004 /// CntInst = CntPhi + 1 2005 /// DefX = PhiX >> 1 2006 /// LOOP_BODY 2007 /// Br: loop if (DefX != 0) 2008 /// Use(CntPhi) or Use(CntInst) 2009 /// 2010 /// Into: 2011 /// If CntPhi used outside the loop: 2012 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) 2013 /// Count = CountPrev + 1 2014 /// else 2015 /// Count = BitWidth(InitX) - CTLZ(InitX) 2016 /// loop: 2017 /// CntPhi = PHI [Cnt0, CntInst] 2018 /// PhiX = PHI [InitX, DefX] 2019 /// PhiCount = PHI [Count, Dec] 2020 /// CntInst = CntPhi + 1 2021 /// DefX = PhiX >> 1 2022 /// Dec = PhiCount - 1 2023 /// LOOP_BODY 2024 /// Br: loop if (Dec != 0) 2025 /// Use(CountPrev + Cnt0) // Use(CntPhi) 2026 /// or 2027 /// Use(Count + Cnt0) // Use(CntInst) 2028 /// 2029 /// If LOOP_BODY is empty the loop will be deleted. 2030 /// If CntInst and DefX are not used in LOOP_BODY they will be removed. 2031 void LoopIdiomRecognize::transformLoopToCountable( 2032 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst, 2033 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL, 2034 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { 2035 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator()); 2036 2037 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block 2038 IRBuilder<> Builder(PreheaderBr); 2039 Builder.SetCurrentDebugLocation(DL); 2040 2041 // If there are no uses of CntPhi crate: 2042 // Count = BitWidth - CTLZ(InitX); 2043 // NewCount = Count; 2044 // If there are uses of CntPhi create: 2045 // NewCount = BitWidth - CTLZ(InitX >> 1); 2046 // Count = NewCount + 1; 2047 Value *InitXNext; 2048 if (IsCntPhiUsedOutsideLoop) { 2049 if (DefX->getOpcode() == Instruction::AShr) 2050 InitXNext = Builder.CreateAShr(InitX, 1); 2051 else if (DefX->getOpcode() == Instruction::LShr) 2052 InitXNext = Builder.CreateLShr(InitX, 1); 2053 else if (DefX->getOpcode() == Instruction::Shl) // cttz 2054 InitXNext = Builder.CreateShl(InitX, 1); 2055 else 2056 llvm_unreachable("Unexpected opcode!"); 2057 } else 2058 InitXNext = InitX; 2059 Value *Count = 2060 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID); 2061 Type *CountTy = Count->getType(); 2062 Count = Builder.CreateSub( 2063 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count); 2064 Value *NewCount = Count; 2065 if (IsCntPhiUsedOutsideLoop) 2066 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1)); 2067 2068 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType()); 2069 2070 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); 2071 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) { 2072 // If the counter was being incremented in the loop, add NewCount to the 2073 // counter's initial value, but only if the initial value is not zero. 2074 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 2075 if (!InitConst || !InitConst->isZero()) 2076 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 2077 } else { 2078 // If the count was being decremented in the loop, subtract NewCount from 2079 // the counter's initial value. 2080 NewCount = Builder.CreateSub(CntInitVal, NewCount); 2081 } 2082 2083 // Step 2: Insert new IV and loop condition: 2084 // loop: 2085 // ... 2086 // PhiCount = PHI [Count, Dec] 2087 // ... 2088 // Dec = PhiCount - 1 2089 // ... 2090 // Br: loop if (Dec != 0) 2091 BasicBlock *Body = *(CurLoop->block_begin()); 2092 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 2093 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 2094 2095 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi", &Body->front()); 2096 2097 Builder.SetInsertPoint(LbCond); 2098 Instruction *TcDec = cast<Instruction>(Builder.CreateSub( 2099 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true)); 2100 2101 TcPhi->addIncoming(Count, Preheader); 2102 TcPhi->addIncoming(TcDec, Body); 2103 2104 CmpInst::Predicate Pred = 2105 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 2106 LbCond->setPredicate(Pred); 2107 LbCond->setOperand(0, TcDec); 2108 LbCond->setOperand(1, ConstantInt::get(CountTy, 0)); 2109 2110 // Step 3: All the references to the original counter outside 2111 // the loop are replaced with the NewCount 2112 if (IsCntPhiUsedOutsideLoop) 2113 CntPhi->replaceUsesOutsideBlock(NewCount, Body); 2114 else 2115 CntInst->replaceUsesOutsideBlock(NewCount, Body); 2116 2117 // step 4: Forget the "non-computable" trip-count SCEV associated with the 2118 // loop. The loop would otherwise not be deleted even if it becomes empty. 2119 SE->forgetLoop(CurLoop); 2120 } 2121 2122 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, 2123 Instruction *CntInst, 2124 PHINode *CntPhi, Value *Var) { 2125 BasicBlock *PreHead = CurLoop->getLoopPreheader(); 2126 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator()); 2127 const DebugLoc &DL = CntInst->getDebugLoc(); 2128 2129 // Assuming before transformation, the loop is following: 2130 // if (x) // the precondition 2131 // do { cnt++; x &= x - 1; } while(x); 2132 2133 // Step 1: Insert the ctpop instruction at the end of the precondition block 2134 IRBuilder<> Builder(PreCondBr); 2135 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; 2136 { 2137 PopCnt = createPopcntIntrinsic(Builder, Var, DL); 2138 NewCount = PopCntZext = 2139 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); 2140 2141 if (NewCount != PopCnt) 2142 (cast<Instruction>(NewCount))->setDebugLoc(DL); 2143 2144 // TripCnt is exactly the number of iterations the loop has 2145 TripCnt = NewCount; 2146 2147 // If the population counter's initial value is not zero, insert Add Inst. 2148 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); 2149 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); 2150 if (!InitConst || !InitConst->isZero()) { 2151 NewCount = Builder.CreateAdd(NewCount, CntInitVal); 2152 (cast<Instruction>(NewCount))->setDebugLoc(DL); 2153 } 2154 } 2155 2156 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to 2157 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic 2158 // function would be partial dead code, and downstream passes will drag 2159 // it back from the precondition block to the preheader. 2160 { 2161 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); 2162 2163 Value *Opnd0 = PopCntZext; 2164 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); 2165 if (PreCond->getOperand(0) != Var) 2166 std::swap(Opnd0, Opnd1); 2167 2168 ICmpInst *NewPreCond = cast<ICmpInst>( 2169 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); 2170 PreCondBr->setCondition(NewPreCond); 2171 2172 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); 2173 } 2174 2175 // Step 3: Note that the population count is exactly the trip count of the 2176 // loop in question, which enable us to convert the loop from noncountable 2177 // loop into a countable one. The benefit is twofold: 2178 // 2179 // - If the loop only counts population, the entire loop becomes dead after 2180 // the transformation. It is a lot easier to prove a countable loop dead 2181 // than to prove a noncountable one. (In some C dialects, an infinite loop 2182 // isn't dead even if it computes nothing useful. In general, DCE needs 2183 // to prove a noncountable loop finite before safely delete it.) 2184 // 2185 // - If the loop also performs something else, it remains alive. 2186 // Since it is transformed to countable form, it can be aggressively 2187 // optimized by some optimizations which are in general not applicable 2188 // to a noncountable loop. 2189 // 2190 // After this step, this loop (conceptually) would look like following: 2191 // newcnt = __builtin_ctpop(x); 2192 // t = newcnt; 2193 // if (x) 2194 // do { cnt++; x &= x-1; t--) } while (t > 0); 2195 BasicBlock *Body = *(CurLoop->block_begin()); 2196 { 2197 auto *LbBr = cast<BranchInst>(Body->getTerminator()); 2198 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); 2199 Type *Ty = TripCnt->getType(); 2200 2201 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); 2202 2203 Builder.SetInsertPoint(LbCond); 2204 Instruction *TcDec = cast<Instruction>( 2205 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), 2206 "tcdec", false, true)); 2207 2208 TcPhi->addIncoming(TripCnt, PreHead); 2209 TcPhi->addIncoming(TcDec, Body); 2210 2211 CmpInst::Predicate Pred = 2212 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; 2213 LbCond->setPredicate(Pred); 2214 LbCond->setOperand(0, TcDec); 2215 LbCond->setOperand(1, ConstantInt::get(Ty, 0)); 2216 } 2217 2218 // Step 4: All the references to the original population counter outside 2219 // the loop are replaced with the NewCount -- the value returned from 2220 // __builtin_ctpop(). 2221 CntInst->replaceUsesOutsideBlock(NewCount, Body); 2222 2223 // step 5: Forget the "non-computable" trip-count SCEV associated with the 2224 // loop. The loop would otherwise not be deleted even if it becomes empty. 2225 SE->forgetLoop(CurLoop); 2226 } 2227 2228 /// Match loop-invariant value. 2229 template <typename SubPattern_t> struct match_LoopInvariant { 2230 SubPattern_t SubPattern; 2231 const Loop *L; 2232 2233 match_LoopInvariant(const SubPattern_t &SP, const Loop *L) 2234 : SubPattern(SP), L(L) {} 2235 2236 template <typename ITy> bool match(ITy *V) { 2237 return L->isLoopInvariant(V) && SubPattern.match(V); 2238 } 2239 }; 2240 2241 /// Matches if the value is loop-invariant. 2242 template <typename Ty> 2243 inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) { 2244 return match_LoopInvariant<Ty>(M, L); 2245 } 2246 2247 /// Return true if the idiom is detected in the loop. 2248 /// 2249 /// The core idiom we are trying to detect is: 2250 /// \code 2251 /// entry: 2252 /// <...> 2253 /// %bitmask = shl i32 1, %bitpos 2254 /// br label %loop 2255 /// 2256 /// loop: 2257 /// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ] 2258 /// %x.curr.bitmasked = and i32 %x.curr, %bitmask 2259 /// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0 2260 /// %x.next = shl i32 %x.curr, 1 2261 /// <...> 2262 /// br i1 %x.curr.isbitunset, label %loop, label %end 2263 /// 2264 /// end: 2265 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2266 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2267 /// <...> 2268 /// \endcode 2269 static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX, 2270 Value *&BitMask, Value *&BitPos, 2271 Value *&CurrX, Instruction *&NextX) { 2272 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2273 " Performing shift-until-bittest idiom detection.\n"); 2274 2275 // Give up if the loop has multiple blocks or multiple backedges. 2276 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) { 2277 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n"); 2278 return false; 2279 } 2280 2281 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2282 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2283 assert(LoopPreheaderBB && "There is always a loop preheader."); 2284 2285 using namespace PatternMatch; 2286 2287 // Step 1: Check if the loop backedge is in desirable form. 2288 2289 ICmpInst::Predicate Pred; 2290 Value *CmpLHS, *CmpRHS; 2291 BasicBlock *TrueBB, *FalseBB; 2292 if (!match(LoopHeaderBB->getTerminator(), 2293 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)), 2294 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) { 2295 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n"); 2296 return false; 2297 } 2298 2299 // Step 2: Check if the backedge's condition is in desirable form. 2300 2301 auto MatchVariableBitMask = [&]() { 2302 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) && 2303 match(CmpLHS, 2304 m_c_And(m_Value(CurrX), 2305 m_CombineAnd( 2306 m_Value(BitMask), 2307 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)), 2308 CurLoop)))); 2309 }; 2310 auto MatchConstantBitMask = [&]() { 2311 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) && 2312 match(CmpLHS, m_And(m_Value(CurrX), 2313 m_CombineAnd(m_Value(BitMask), m_Power2()))) && 2314 (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask))); 2315 }; 2316 auto MatchDecomposableConstantBitMask = [&]() { 2317 APInt Mask; 2318 return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) && 2319 ICmpInst::isEquality(Pred) && Mask.isPowerOf2() && 2320 (BitMask = ConstantInt::get(CurrX->getType(), Mask)) && 2321 (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2())); 2322 }; 2323 2324 if (!MatchVariableBitMask() && !MatchConstantBitMask() && 2325 !MatchDecomposableConstantBitMask()) { 2326 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n"); 2327 return false; 2328 } 2329 2330 // Step 3: Check if the recurrence is in desirable form. 2331 auto *CurrXPN = dyn_cast<PHINode>(CurrX); 2332 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) { 2333 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n"); 2334 return false; 2335 } 2336 2337 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB); 2338 NextX = 2339 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB)); 2340 2341 assert(CurLoop->isLoopInvariant(BaseX) && 2342 "Expected BaseX to be avaliable in the preheader!"); 2343 2344 if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) { 2345 // FIXME: support right-shift? 2346 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n"); 2347 return false; 2348 } 2349 2350 // Step 4: Check if the backedge's destinations are in desirable form. 2351 2352 assert(ICmpInst::isEquality(Pred) && 2353 "Should only get equality predicates here."); 2354 2355 // cmp-br is commutative, so canonicalize to a single variant. 2356 if (Pred != ICmpInst::Predicate::ICMP_EQ) { 2357 Pred = ICmpInst::getInversePredicate(Pred); 2358 std::swap(TrueBB, FalseBB); 2359 } 2360 2361 // We expect to exit loop when comparison yields false, 2362 // so when it yields true we should branch back to loop header. 2363 if (TrueBB != LoopHeaderBB) { 2364 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n"); 2365 return false; 2366 } 2367 2368 // Okay, idiom checks out. 2369 return true; 2370 } 2371 2372 /// Look for the following loop: 2373 /// \code 2374 /// entry: 2375 /// <...> 2376 /// %bitmask = shl i32 1, %bitpos 2377 /// br label %loop 2378 /// 2379 /// loop: 2380 /// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ] 2381 /// %x.curr.bitmasked = and i32 %x.curr, %bitmask 2382 /// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0 2383 /// %x.next = shl i32 %x.curr, 1 2384 /// <...> 2385 /// br i1 %x.curr.isbitunset, label %loop, label %end 2386 /// 2387 /// end: 2388 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2389 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2390 /// <...> 2391 /// \endcode 2392 /// 2393 /// And transform it into: 2394 /// \code 2395 /// entry: 2396 /// %bitmask = shl i32 1, %bitpos 2397 /// %lowbitmask = add i32 %bitmask, -1 2398 /// %mask = or i32 %lowbitmask, %bitmask 2399 /// %x.masked = and i32 %x, %mask 2400 /// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked, 2401 /// i1 true) 2402 /// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros 2403 /// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1 2404 /// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos 2405 /// %tripcount = add i32 %backedgetakencount, 1 2406 /// %x.curr = shl i32 %x, %backedgetakencount 2407 /// %x.next = shl i32 %x, %tripcount 2408 /// br label %loop 2409 /// 2410 /// loop: 2411 /// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ] 2412 /// %loop.iv.next = add nuw i32 %loop.iv, 1 2413 /// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount 2414 /// <...> 2415 /// br i1 %loop.ivcheck, label %end, label %loop 2416 /// 2417 /// end: 2418 /// %x.curr.res = phi i32 [ %x.curr, %loop ] <...> 2419 /// %x.next.res = phi i32 [ %x.next, %loop ] <...> 2420 /// <...> 2421 /// \endcode 2422 bool LoopIdiomRecognize::recognizeShiftUntilBitTest() { 2423 bool MadeChange = false; 2424 2425 Value *X, *BitMask, *BitPos, *XCurr; 2426 Instruction *XNext; 2427 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr, 2428 XNext)) { 2429 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2430 " shift-until-bittest idiom detection failed.\n"); 2431 return MadeChange; 2432 } 2433 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n"); 2434 2435 // Ok, it is the idiom we were looking for, we *could* transform this loop, 2436 // but is it profitable to transform? 2437 2438 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2439 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2440 assert(LoopPreheaderBB && "There is always a loop preheader."); 2441 2442 BasicBlock *SuccessorBB = CurLoop->getExitBlock(); 2443 assert(SuccessorBB && "There is only a single successor."); 2444 2445 IRBuilder<> Builder(LoopPreheaderBB->getTerminator()); 2446 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc()); 2447 2448 Intrinsic::ID IntrID = Intrinsic::ctlz; 2449 Type *Ty = X->getType(); 2450 unsigned Bitwidth = Ty->getScalarSizeInBits(); 2451 2452 TargetTransformInfo::TargetCostKind CostKind = 2453 TargetTransformInfo::TCK_SizeAndLatency; 2454 2455 // The rewrite is considered to be unprofitable iff and only iff the 2456 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just* 2457 // making the loop countable, even if nothing else changes. 2458 IntrinsicCostAttributes Attrs( 2459 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getTrue()}); 2460 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind); 2461 if (Cost > TargetTransformInfo::TCC_Basic) { 2462 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2463 " Intrinsic is too costly, not beneficial\n"); 2464 return MadeChange; 2465 } 2466 if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) > 2467 TargetTransformInfo::TCC_Basic) { 2468 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n"); 2469 return MadeChange; 2470 } 2471 2472 // Ok, transform appears worthwhile. 2473 MadeChange = true; 2474 2475 // Step 1: Compute the loop trip count. 2476 2477 Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty), 2478 BitPos->getName() + ".lowbitmask"); 2479 Value *Mask = 2480 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask"); 2481 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked"); 2482 CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic( 2483 IntrID, Ty, {XMasked, /*is_zero_undef=*/Builder.getTrue()}, 2484 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros"); 2485 Value *XMaskedNumActiveBits = Builder.CreateSub( 2486 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros, 2487 XMasked->getName() + ".numactivebits", /*HasNUW=*/true, 2488 /*HasNSW=*/Bitwidth != 2); 2489 Value *XMaskedLeadingOnePos = 2490 Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty), 2491 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false, 2492 /*HasNSW=*/Bitwidth > 2); 2493 2494 Value *LoopBackedgeTakenCount = Builder.CreateSub( 2495 BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount", 2496 /*HasNUW=*/true, /*HasNSW=*/true); 2497 // We know loop's backedge-taken count, but what's loop's trip count? 2498 // Note that while NUW is always safe, while NSW is only for bitwidths != 2. 2499 Value *LoopTripCount = 2500 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1), 2501 CurLoop->getName() + ".tripcount", /*HasNUW=*/true, 2502 /*HasNSW=*/Bitwidth != 2); 2503 2504 // Step 2: Compute the recurrence's final value without a loop. 2505 2506 // NewX is always safe to compute, because `LoopBackedgeTakenCount` 2507 // will always be smaller than `bitwidth(X)`, i.e. we never get poison. 2508 Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount); 2509 NewX->takeName(XCurr); 2510 if (auto *I = dyn_cast<Instruction>(NewX)) 2511 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true); 2512 2513 Value *NewXNext; 2514 // Rewriting XNext is more complicated, however, because `X << LoopTripCount` 2515 // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen 2516 // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know 2517 // that isn't the case, we'll need to emit an alternative, safe IR. 2518 if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() || 2519 PatternMatch::match( 2520 BitPos, PatternMatch::m_SpecificInt_ICMP( 2521 ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(), 2522 Ty->getScalarSizeInBits() - 1)))) 2523 NewXNext = Builder.CreateShl(X, LoopTripCount); 2524 else { 2525 // Otherwise, just additionally shift by one. It's the smallest solution, 2526 // alternatively, we could check that NewX is INT_MIN (or BitPos is ) 2527 // and select 0 instead. 2528 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1)); 2529 } 2530 2531 NewXNext->takeName(XNext); 2532 if (auto *I = dyn_cast<Instruction>(NewXNext)) 2533 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true); 2534 2535 // Step 3: Adjust the successor basic block to recieve the computed 2536 // recurrence's final value instead of the recurrence itself. 2537 2538 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB); 2539 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB); 2540 2541 // Step 4: Rewrite the loop into a countable form, with canonical IV. 2542 2543 // The new canonical induction variable. 2544 Builder.SetInsertPoint(&LoopHeaderBB->front()); 2545 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv"); 2546 2547 // The induction itself. 2548 // Note that while NUW is always safe, while NSW is only for bitwidths != 2. 2549 Builder.SetInsertPoint(LoopHeaderBB->getTerminator()); 2550 auto *IVNext = 2551 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next", 2552 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2); 2553 2554 // The loop trip count check. 2555 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount, 2556 CurLoop->getName() + ".ivcheck"); 2557 Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB); 2558 LoopHeaderBB->getTerminator()->eraseFromParent(); 2559 2560 // Populate the IV PHI. 2561 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB); 2562 IV->addIncoming(IVNext, LoopHeaderBB); 2563 2564 // Step 5: Forget the "non-computable" trip-count SCEV associated with the 2565 // loop. The loop would otherwise not be deleted even if it becomes empty. 2566 2567 SE->forgetLoop(CurLoop); 2568 2569 // Other passes will take care of actually deleting the loop if possible. 2570 2571 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n"); 2572 2573 ++NumShiftUntilBitTest; 2574 return MadeChange; 2575 } 2576 2577 /// Return true if the idiom is detected in the loop. 2578 /// 2579 /// The core idiom we are trying to detect is: 2580 /// \code 2581 /// entry: 2582 /// <...> 2583 /// %start = <...> 2584 /// %extraoffset = <...> 2585 /// <...> 2586 /// br label %for.cond 2587 /// 2588 /// loop: 2589 /// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ] 2590 /// %nbits = add nsw i8 %iv, %extraoffset 2591 /// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits 2592 /// %val.shifted.iszero = icmp eq i8 %val.shifted, 0 2593 /// %iv.next = add i8 %iv, 1 2594 /// <...> 2595 /// br i1 %val.shifted.iszero, label %end, label %loop 2596 /// 2597 /// end: 2598 /// %iv.res = phi i8 [ %iv, %loop ] <...> 2599 /// %nbits.res = phi i8 [ %nbits, %loop ] <...> 2600 /// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...> 2601 /// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...> 2602 /// %iv.next.res = phi i8 [ %iv.next, %loop ] <...> 2603 /// <...> 2604 /// \endcode 2605 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE, 2606 Instruction *&ValShiftedIsZero, 2607 Intrinsic::ID &IntrinID, Instruction *&IV, 2608 Value *&Start, Value *&Val, 2609 const SCEV *&ExtraOffsetExpr, 2610 bool &InvertedCond) { 2611 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2612 " Performing shift-until-zero idiom detection.\n"); 2613 2614 // Give up if the loop has multiple blocks or multiple backedges. 2615 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) { 2616 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n"); 2617 return false; 2618 } 2619 2620 Instruction *ValShifted, *NBits, *IVNext; 2621 Value *ExtraOffset; 2622 2623 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2624 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2625 assert(LoopPreheaderBB && "There is always a loop preheader."); 2626 2627 using namespace PatternMatch; 2628 2629 // Step 1: Check if the loop backedge, condition is in desirable form. 2630 2631 ICmpInst::Predicate Pred; 2632 BasicBlock *TrueBB, *FalseBB; 2633 if (!match(LoopHeaderBB->getTerminator(), 2634 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB), 2635 m_BasicBlock(FalseBB))) || 2636 !match(ValShiftedIsZero, 2637 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) || 2638 !ICmpInst::isEquality(Pred)) { 2639 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n"); 2640 return false; 2641 } 2642 2643 // Step 2: Check if the comparison's operand is in desirable form. 2644 // FIXME: Val could be a one-input PHI node, which we should look past. 2645 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop), 2646 m_Instruction(NBits)))) { 2647 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n"); 2648 return false; 2649 } 2650 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz 2651 : Intrinsic::ctlz; 2652 2653 // Step 3: Check if the shift amount is in desirable form. 2654 2655 if (match(NBits, m_c_Add(m_Instruction(IV), 2656 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) && 2657 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap())) 2658 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset)); 2659 else if (match(NBits, 2660 m_Sub(m_Instruction(IV), 2661 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) && 2662 NBits->hasNoSignedWrap()) 2663 ExtraOffsetExpr = SE->getSCEV(ExtraOffset); 2664 else { 2665 IV = NBits; 2666 ExtraOffsetExpr = SE->getZero(NBits->getType()); 2667 } 2668 2669 // Step 4: Check if the recurrence is in desirable form. 2670 auto *IVPN = dyn_cast<PHINode>(IV); 2671 if (!IVPN || IVPN->getParent() != LoopHeaderBB) { 2672 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n"); 2673 return false; 2674 } 2675 2676 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB); 2677 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB)); 2678 2679 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) { 2680 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n"); 2681 return false; 2682 } 2683 2684 // Step 4: Check if the backedge's destinations are in desirable form. 2685 2686 assert(ICmpInst::isEquality(Pred) && 2687 "Should only get equality predicates here."); 2688 2689 // cmp-br is commutative, so canonicalize to a single variant. 2690 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ; 2691 if (InvertedCond) { 2692 Pred = ICmpInst::getInversePredicate(Pred); 2693 std::swap(TrueBB, FalseBB); 2694 } 2695 2696 // We expect to exit loop when comparison yields true, 2697 // so when it yields false we should branch back to loop header. 2698 if (FalseBB != LoopHeaderBB) { 2699 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n"); 2700 return false; 2701 } 2702 2703 // The new, countable, loop will certainly only run a known number of 2704 // iterations, It won't be infinite. But the old loop might be infinite 2705 // under certain conditions. For logical shifts, the value will become zero 2706 // after at most bitwidth(%Val) loop iterations. However, for arithmetic 2707 // right-shift, iff the sign bit was set, the value will never become zero, 2708 // and the loop may never finish. 2709 if (ValShifted->getOpcode() == Instruction::AShr && 2710 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) { 2711 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n"); 2712 return false; 2713 } 2714 2715 // Okay, idiom checks out. 2716 return true; 2717 } 2718 2719 /// Look for the following loop: 2720 /// \code 2721 /// entry: 2722 /// <...> 2723 /// %start = <...> 2724 /// %extraoffset = <...> 2725 /// <...> 2726 /// br label %for.cond 2727 /// 2728 /// loop: 2729 /// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ] 2730 /// %nbits = add nsw i8 %iv, %extraoffset 2731 /// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits 2732 /// %val.shifted.iszero = icmp eq i8 %val.shifted, 0 2733 /// %iv.next = add i8 %iv, 1 2734 /// <...> 2735 /// br i1 %val.shifted.iszero, label %end, label %loop 2736 /// 2737 /// end: 2738 /// %iv.res = phi i8 [ %iv, %loop ] <...> 2739 /// %nbits.res = phi i8 [ %nbits, %loop ] <...> 2740 /// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...> 2741 /// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...> 2742 /// %iv.next.res = phi i8 [ %iv.next, %loop ] <...> 2743 /// <...> 2744 /// \endcode 2745 /// 2746 /// And transform it into: 2747 /// \code 2748 /// entry: 2749 /// <...> 2750 /// %start = <...> 2751 /// %extraoffset = <...> 2752 /// <...> 2753 /// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0) 2754 /// %val.numactivebits = sub i8 8, %val.numleadingzeros 2755 /// %extraoffset.neg = sub i8 0, %extraoffset 2756 /// %tmp = add i8 %val.numactivebits, %extraoffset.neg 2757 /// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start) 2758 /// %loop.tripcount = sub i8 %iv.final, %start 2759 /// br label %loop 2760 /// 2761 /// loop: 2762 /// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ] 2763 /// %loop.iv.next = add i8 %loop.iv, 1 2764 /// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount 2765 /// %iv = add i8 %loop.iv, %start 2766 /// <...> 2767 /// br i1 %loop.ivcheck, label %end, label %loop 2768 /// 2769 /// end: 2770 /// %iv.res = phi i8 [ %iv.final, %loop ] <...> 2771 /// <...> 2772 /// \endcode 2773 bool LoopIdiomRecognize::recognizeShiftUntilZero() { 2774 bool MadeChange = false; 2775 2776 Instruction *ValShiftedIsZero; 2777 Intrinsic::ID IntrID; 2778 Instruction *IV; 2779 Value *Start, *Val; 2780 const SCEV *ExtraOffsetExpr; 2781 bool InvertedCond; 2782 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV, 2783 Start, Val, ExtraOffsetExpr, InvertedCond)) { 2784 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2785 " shift-until-zero idiom detection failed.\n"); 2786 return MadeChange; 2787 } 2788 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n"); 2789 2790 // Ok, it is the idiom we were looking for, we *could* transform this loop, 2791 // but is it profitable to transform? 2792 2793 BasicBlock *LoopHeaderBB = CurLoop->getHeader(); 2794 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader(); 2795 assert(LoopPreheaderBB && "There is always a loop preheader."); 2796 2797 BasicBlock *SuccessorBB = CurLoop->getExitBlock(); 2798 assert(SuccessorBB && "There is only a single successor."); 2799 2800 IRBuilder<> Builder(LoopPreheaderBB->getTerminator()); 2801 Builder.SetCurrentDebugLocation(IV->getDebugLoc()); 2802 2803 Type *Ty = Val->getType(); 2804 unsigned Bitwidth = Ty->getScalarSizeInBits(); 2805 2806 TargetTransformInfo::TargetCostKind CostKind = 2807 TargetTransformInfo::TCK_SizeAndLatency; 2808 2809 // The rewrite is considered to be unprofitable iff and only iff the 2810 // intrinsic we'll use are not cheap. Note that we are okay with *just* 2811 // making the loop countable, even if nothing else changes. 2812 IntrinsicCostAttributes Attrs( 2813 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getFalse()}); 2814 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind); 2815 if (Cost > TargetTransformInfo::TCC_Basic) { 2816 LLVM_DEBUG(dbgs() << DEBUG_TYPE 2817 " Intrinsic is too costly, not beneficial\n"); 2818 return MadeChange; 2819 } 2820 2821 // Ok, transform appears worthwhile. 2822 MadeChange = true; 2823 2824 bool OffsetIsZero = false; 2825 if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr)) 2826 OffsetIsZero = ExtraOffsetExprC->isZero(); 2827 2828 // Step 1: Compute the loop's final IV value / trip count. 2829 2830 CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic( 2831 IntrID, Ty, {Val, /*is_zero_undef=*/Builder.getFalse()}, 2832 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros"); 2833 Value *ValNumActiveBits = Builder.CreateSub( 2834 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros, 2835 Val->getName() + ".numactivebits", /*HasNUW=*/true, 2836 /*HasNSW=*/Bitwidth != 2); 2837 2838 SCEVExpander Expander(*SE, *DL, "loop-idiom"); 2839 Expander.setInsertPoint(&*Builder.GetInsertPoint()); 2840 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr); 2841 2842 Value *ValNumActiveBitsOffset = Builder.CreateAdd( 2843 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset", 2844 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true); 2845 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty}, 2846 {ValNumActiveBitsOffset, Start}, 2847 /*FMFSource=*/nullptr, "iv.final"); 2848 2849 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub( 2850 IVFinal, Start, CurLoop->getName() + ".backedgetakencount", 2851 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true)); 2852 // FIXME: or when the offset was `add nuw` 2853 2854 // We know loop's backedge-taken count, but what's loop's trip count? 2855 Value *LoopTripCount = 2856 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1), 2857 CurLoop->getName() + ".tripcount", /*HasNUW=*/true, 2858 /*HasNSW=*/Bitwidth != 2); 2859 2860 // Step 2: Adjust the successor basic block to recieve the original 2861 // induction variable's final value instead of the orig. IV itself. 2862 2863 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB); 2864 2865 // Step 3: Rewrite the loop into a countable form, with canonical IV. 2866 2867 // The new canonical induction variable. 2868 Builder.SetInsertPoint(&LoopHeaderBB->front()); 2869 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv"); 2870 2871 // The induction itself. 2872 Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHI()); 2873 auto *CIVNext = 2874 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next", 2875 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2); 2876 2877 // The loop trip count check. 2878 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount, 2879 CurLoop->getName() + ".ivcheck"); 2880 auto *NewIVCheck = CIVCheck; 2881 if (InvertedCond) { 2882 NewIVCheck = Builder.CreateNot(CIVCheck); 2883 NewIVCheck->takeName(ValShiftedIsZero); 2884 } 2885 2886 // The original IV, but rebased to be an offset to the CIV. 2887 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false, 2888 /*HasNSW=*/true); // FIXME: what about NUW? 2889 IVDePHId->takeName(IV); 2890 2891 // The loop terminator. 2892 Builder.SetInsertPoint(LoopHeaderBB->getTerminator()); 2893 Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB); 2894 LoopHeaderBB->getTerminator()->eraseFromParent(); 2895 2896 // Populate the IV PHI. 2897 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB); 2898 CIV->addIncoming(CIVNext, LoopHeaderBB); 2899 2900 // Step 4: Forget the "non-computable" trip-count SCEV associated with the 2901 // loop. The loop would otherwise not be deleted even if it becomes empty. 2902 2903 SE->forgetLoop(CurLoop); 2904 2905 // Step 5: Try to cleanup the loop's body somewhat. 2906 IV->replaceAllUsesWith(IVDePHId); 2907 IV->eraseFromParent(); 2908 2909 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck); 2910 ValShiftedIsZero->eraseFromParent(); 2911 2912 // Other passes will take care of actually deleting the loop if possible. 2913 2914 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n"); 2915 2916 ++NumShiftUntilZero; 2917 return MadeChange; 2918 } 2919