LLVM 24.0.0git
LoopIdiomRecognize.cpp
Go to the documentation of this file.
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: memcmp, etc.
24//
25// This could recognize common matrix multiplies and dot product idioms and
26// replace them with calls to BLAS (if linked in??).
27//
28//===----------------------------------------------------------------------===//
29
31#include "ScalarOptions.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SetVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringRef.h"
59#include "llvm/IR/BasicBlock.h"
60#include "llvm/IR/Constant.h"
61#include "llvm/IR/Constants.h"
62#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/DebugLoc.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/GlobalValue.h"
68#include "llvm/IR/IRBuilder.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
73#include "llvm/IR/Intrinsics.h"
74#include "llvm/IR/LLVMContext.h"
75#include "llvm/IR/Module.h"
76#include "llvm/IR/PassManager.h"
79#include "llvm/IR/Type.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
85#include "llvm/Support/Debug.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <utility>
96
97using namespace llvm;
98using namespace SCEVPatternMatch;
99
100#define DEBUG_TYPE "loop-idiom"
101
102STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
103STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
104STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");
105STATISTIC(NumStrLen, "Number of strlen's and wcslen's formed from loop loads");
107 NumShiftUntilBitTest,
108 "Number of uncountable loops recognized as 'shift until bitttest' idiom");
109STATISTIC(NumShiftUntilZero,
110 "Number of uncountable loops recognized as 'shift until zero' idiom");
111
112namespace llvm {
115 DisableLIRPAll("disable-" DEBUG_TYPE "-all",
116 cl::desc("Options to disable Loop Idiom Recognize Pass."),
119
122 DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",
123 cl::desc("Proceed with loop idiom recognize pass, but do "
124 "not convert loop(s) to memset."),
127
130 DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",
131 cl::desc("Proceed with loop idiom recognize pass, but do "
132 "not convert loop(s) to memcpy."),
135
138 DisableLIRPStrlen("disable-loop-idiom-strlen",
139 cl::desc("Proceed with loop idiom recognize pass, but do "
140 "not convert loop(s) to strlen."),
143
146 EnableLIRPWcslen("disable-loop-idiom-wcslen",
147 cl::desc("Proceed with loop idiom recognize pass, "
148 "enable conversion of loop(s) to wcslen."),
151
154 DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize",
155 cl::desc("Proceed with loop idiom recognize pass, "
156 "but do not do hash-recognize analysis."),
158 cl::init(false), cl::ReallyHidden);
159
160} // namespace llvm
161
162namespace {
163
164class LoopIdiomRecognize {
165 const ScalarOptions &Opts;
166 Loop *CurLoop = nullptr;
168 DominatorTree *DT;
169 LoopInfo *LI;
170 ScalarEvolution *SE;
173 const DataLayout *DL;
175 bool ApplyCodeSizeHeuristics;
176 std::unique_ptr<MemorySSAUpdater> MSSAU;
177
178public:
179 explicit LoopIdiomRecognize(const ScalarOptions &Opts, AliasAnalysis *AA,
180 DominatorTree *DT, LoopInfo *LI,
182 const TargetTransformInfo *TTI, MemorySSA *MSSA,
183 const DataLayout *DL,
185 : Opts(Opts), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL),
186 ORE(ORE) {
187 if (MSSA)
188 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
189 }
190
191 bool runOnLoop(Loop *L);
192
193private:
194 using StoreList = SmallVector<StoreInst *, 8>;
195 using StoreListMap = MapVector<Value *, StoreList>;
196
197 StoreListMap StoreRefsForMemset;
198 StoreListMap StoreRefsForMemsetPattern;
199 StoreList StoreRefsForMemcpy;
200 bool HasMemset;
201 bool HasMemsetPattern;
202 bool HasMemcpy;
203
204 /// Return code for isLegalStore()
205 enum LegalStoreKind {
206 None = 0,
207 Memset,
208 MemsetPattern,
209 Memcpy,
210 UnorderedAtomicMemcpy,
211 DontUse // Dummy retval never to be used. Allows catching errors in retval
212 // handling.
213 };
214
215 /// \name Countable Loop Idiom Handling
216 /// @{
217
218 bool runOnCountableLoop();
219 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
220 SmallVectorImpl<BasicBlock *> &ExitBlocks);
221
222 void collectStores(BasicBlock *BB);
223 LegalStoreKind isLegalStore(StoreInst *SI);
224 enum class ForMemset { No, Yes };
225 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
226 ForMemset For);
227
228 template <typename MemInst>
229 bool processLoopMemIntrinsic(
230 BasicBlock *BB,
231 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
232 const SCEV *BECount);
233 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
234 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
235
236 bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,
237 MaybeAlign StoreAlignment, Value *StoredVal,
238 Instruction *TheStore,
239 SmallPtrSetImpl<Instruction *> &Stores,
240 const SCEVAddRecExpr *Ev, const SCEV *BECount,
241 bool IsNegStride, bool IsLoopMemset = false);
242 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
243 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
244 const SCEV *StoreSize, MaybeAlign StoreAlign,
245 MaybeAlign LoadAlign, Instruction *TheStore,
246 Instruction *TheLoad,
247 const SCEVAddRecExpr *StoreEv,
248 const SCEVAddRecExpr *LoadEv,
249 const SCEV *BECount);
250 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
251 bool IsLoopMemset = false);
252 bool optimizeCRCLoop(const PolynomialInfo &Info);
253 void optimizeCRCLoopUsingClmul(const PolynomialInfo &Info);
254 void optimizeCRCLoopUsingTableLookup(const PolynomialInfo &Info);
255
256 /// @}
257 /// \name Noncountable Loop Idiom Handling
258 /// @{
259
260 bool runOnNoncountableLoop();
261
262 bool recognizePopcount();
263 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
264 PHINode *CntPhi, Value *Var);
265 bool isProfitableToInsertFFS(Intrinsic::ID IntrinID, Value *InitX,
266 bool ZeroCheck, size_t CanonicalSize);
267 bool insertFFSIfProfitable(Intrinsic::ID IntrinID, Value *InitX,
268 Instruction *DefX, PHINode *CntPhi,
269 Instruction *CntInst);
270 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz
271 bool recognizeShiftUntilLessThan();
272 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
273 Instruction *CntInst, PHINode *CntPhi,
274 Value *Var, Instruction *DefX,
275 const DebugLoc &DL, bool ZeroCheck,
276 bool IsCntPhiUsedOutsideLoop,
277 bool InsertSub = false);
278
279 bool recognizeShiftUntilBitTest();
280 bool recognizeShiftUntilZero();
281 bool recognizeAndInsertStrLen();
282
283 /// @}
284};
285} // end anonymous namespace
286
289 LPMUpdater &) {
291 return PreservedAnalyses::all();
292
293 const auto *DL = &L.getHeader()->getDataLayout();
294
295 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
296 // pass. Function analyses need to be preserved across loop transformations
297 // but ORE cannot be preserved (see comment before the pass definition).
298 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
299
300 const ScalarOptions &Opts = getScalarOptions(L);
301 LoopIdiomRecognize LIR(Opts, &AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
302 AR.MSSA, DL, ORE);
303 if (!LIR.runOnLoop(&L))
304 return PreservedAnalyses::all();
305
307 if (AR.MSSA)
308 PA.preserve<MemorySSAAnalysis>();
309 return PA;
310}
311
313 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
314 I->eraseFromParent();
315}
316
317//===----------------------------------------------------------------------===//
318//
319// Implementation of LoopIdiomRecognize
320//
321//===----------------------------------------------------------------------===//
322
323bool LoopIdiomRecognize::runOnLoop(Loop *L) {
324 CurLoop = L;
325 // If the loop could not be converted to canonical form, it must have an
326 // indirectbr in it, just give up.
327 if (!L->getLoopPreheader())
328 return false;
329
330 // Disable loop idiom recognition if the function's name is a common idiom.
331 StringRef Name = L->getHeader()->getParent()->getName();
332 if (Name == "memset" || Name == "memcpy" || Name == "strlen" ||
333 Name == "wcslen")
334 return false;
335
336 // Determine if code size heuristics need to be applied.
337 ApplyCodeSizeHeuristics =
338 L->getHeader()->getParent()->hasOptSize() && Opts.use_lir_code_size_heurs;
339
340 HasMemset = TLI->has(LibFunc_memset);
341 // TODO: Unconditionally enable use of the memset pattern intrinsic (or at
342 // least, opt-in via target hook) once we are confident it will never result
343 // in worse codegen than without. For now, use it only when the target
344 // supports memset_pattern16 libcall (or unless this is overridden by
345 // command line option).
346 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
347 HasMemcpy = TLI->has(LibFunc_memcpy);
348
349 if (HasMemset || HasMemsetPattern ||
350 Opts.loop_idiom_force_memset_pattern_intrinsic || HasMemcpy ||
353 return runOnCountableLoop();
354
355 return runOnNoncountableLoop();
356}
357
358bool LoopIdiomRecognize::runOnCountableLoop() {
359 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
361 "runOnCountableLoop() called on a loop without a predictable"
362 "backedge-taken count");
363
364 // If this loop executes exactly one time, then it should be peeled, not
365 // optimized by this pass.
366 if (BECount->isZero())
367 return false;
368
370 CurLoop->getUniqueExitBlocks(ExitBlocks);
371
372 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
373 << CurLoop->getHeader()->getParent()->getName()
374 << "] Countable Loop %" << CurLoop->getHeader()->getName()
375 << "\n");
376
377 // The following transforms hoist stores/memsets into the loop pre-header.
378 // Give up if the loop has instructions that may throw.
379 SimpleLoopSafetyInfo SafetyInfo(CurLoop);
380 if (SafetyInfo.anyBlockMayThrow())
381 return false;
382
383 bool MadeChange = false;
384
385 // Scan all the blocks in the loop that are not in subloops.
386 for (auto *BB : CurLoop->getBlocks()) {
387 // Ignore blocks in subloops.
388 if (LI->getLoopFor(BB) != CurLoop)
389 continue;
390
391 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
392 }
393
394 // Attempt to optimize a CRC loop if one is detected by HashRecognize.
396 Opts.loop_idiom_crc_strategy != CRCStrategyKind::Disable)
397 if (auto Res = HashRecognize(*CurLoop, *SE).getResult())
398 MadeChange |= optimizeCRCLoop(*Res);
399
400 return MadeChange;
401}
402
403static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
404 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
405 return ConstStride->getAPInt();
406}
407
408/// getMemSetPatternValue - If a strided store of the specified value is safe to
409/// turn into a memset.patternn intrinsic, return the Constant that should
410/// be passed in. Otherwise, return null.
411///
412/// TODO this function could allow more constants than it does today (e.g.
413/// those over 16 bytes) now it has transitioned to being used for the
414/// memset.pattern intrinsic rather than directly the memset_pattern16
415/// libcall.
417 // FIXME: This could check for UndefValue because it can be merged into any
418 // other valid pattern.
419
420 // If the value isn't a constant, we can't promote it to being in a constant
421 // array. We could theoretically do a store to an alloca or something, but
422 // that doesn't seem worthwhile.
424 if (!C || isa<ConstantExpr>(C))
425 return nullptr;
426
427 // Only handle simple values that are a power of two bytes in size.
428 uint64_t Size = DL->getTypeSizeInBits(V->getType());
429 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
430 return nullptr;
431
432 // Don't care enough about darwin/ppc to implement this.
433 if (DL->isBigEndian())
434 return nullptr;
435
436 // Convert to size in bytes.
437 Size /= 8;
438
439 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
440 // if the top and bottom are the same (e.g. for vectors and large integers).
441 if (Size > 16)
442 return nullptr;
443
444 // For now, don't handle types that aren't int, floats, or pointers.
445 Type *CTy = C->getType();
446 if (!CTy->isIntOrPtrTy() && !CTy->isFloatingPointTy())
447 return nullptr;
448
449 return C;
450}
451
452LoopIdiomRecognize::LegalStoreKind
453LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
454 // Don't touch volatile stores.
455 if (SI->isVolatile())
456 return LegalStoreKind::None;
457 // We only want simple or unordered-atomic stores.
458 if (!SI->isUnordered())
459 return LegalStoreKind::None;
460
461 // Avoid merging nontemporal stores.
462 if (SI->getMetadata(LLVMContext::MD_nontemporal))
463 return LegalStoreKind::None;
464
465 Value *StoredVal = SI->getValueOperand();
466 Value *StorePtr = SI->getPointerOperand();
467
468 if (DL->hasUnstableRepresentation(StoredVal->getType()))
469 return LegalStoreKind::None;
470
471 // Transformations could invalidate the external-state pointers
472 // memcpy - LangRef specifies that a valid memcpy must preserve external
473 // state, so no transformations are blocked by it.
474 // memset - We assume that a memset of 0 has an equivalent external state
475 // effect as a null pointer store. This is currently not explicitly
476 // specified, but is true of the one exemplar we have (CHERI
477 // capabilities). All other memset formations are not safe.
478 bool MustPreserveExternalState = DL->hasExternalState(StoredVal->getType()) &&
479 !isa<ConstantPointerNull>(StoredVal);
480
481 // Reject stores that are so large that they overflow an unsigned.
482 // When storing out scalable vectors we bail out for now, since the code
483 // below currently only works for constant strides.
484 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
485 if (SizeInBits.isScalable() || (SizeInBits.getFixedValue() & 7) ||
486 (SizeInBits.getFixedValue() >> 32) != 0)
487 return LegalStoreKind::None;
488
489 // See if the pointer expression is an AddRec like {base,+,1} on the current
490 // loop, which indicates a strided store. If we have something else, it's a
491 // random store we can't handle.
492 const SCEV *StoreEv = SE->getSCEV(StorePtr);
493 const SCEVConstant *Stride;
494 if (!match(StoreEv, m_scev_AffineAddRec(m_SCEV(), m_SCEVConstant(Stride),
495 m_SpecificLoop(CurLoop))))
496 return LegalStoreKind::None;
497
498 // See if the store can be turned into a memset.
499
500 // If the stored value is a byte-wise value (like i32 -1), then it may be
501 // turned into a memset of i8 -1, assuming that all the consecutive bytes
502 // are stored. A store of i32 0x01020304 can never be turned into a memset,
503 // but it can be turned into memset_pattern if the target supports it.
504 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
505
506 // Note: memset and memset_pattern on unordered-atomic is yet not supported
507 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
508
509 // If we're allowed to form a memset, and the stored value would be
510 // acceptable for memset, use it.
511 if (!MustPreserveExternalState && !UnorderedAtomic && HasMemset &&
512 SplatValue && !DisableLIRP::Memset &&
513 // Verify that the stored value is loop invariant. If not, we can't
514 // promote the memset.
515 CurLoop->isLoopInvariant(SplatValue)) {
516 // It looks like we can use SplatValue.
517 return LegalStoreKind::Memset;
518 }
519 if (!MustPreserveExternalState && !UnorderedAtomic &&
520 (HasMemsetPattern || Opts.loop_idiom_force_memset_pattern_intrinsic) &&
522 // Don't create memset_pattern16s with address spaces.
523 StorePtr->getType()->getPointerAddressSpace() == 0 &&
524 getMemSetPatternValue(StoredVal, DL)) {
525 // It looks like we can use PatternValue!
526 return LegalStoreKind::MemsetPattern;
527 }
528
529 // Otherwise, see if the store can be turned into a memcpy.
530 if (HasMemcpy && !DisableLIRP::Memcpy) {
531 // Check to see if the stride matches the size of the store. If so, then we
532 // know that every byte is touched in the loop.
533 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
534 APInt StrideAP = Stride->getAPInt();
535 if (StoreSize != StrideAP && StoreSize != -StrideAP)
536 return LegalStoreKind::None;
537
538 // The store must be feeding a non-volatile load.
539 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
540
541 // Only allow non-volatile loads
542 if (!LI || LI->isVolatile())
543 return LegalStoreKind::None;
544 // Only allow simple or unordered-atomic loads
545 if (!LI->isUnordered())
546 return LegalStoreKind::None;
547
548 // See if the pointer expression is an AddRec like {base,+,1} on the current
549 // loop, which indicates a strided load. If we have something else, it's a
550 // random load we can't handle.
551 const SCEV *LoadEv = SE->getSCEV(LI->getPointerOperand());
552
553 // The store and load must share the same stride.
554 if (!match(LoadEv, m_scev_AffineAddRec(m_SCEV(), m_scev_Specific(Stride),
555 m_SpecificLoop(CurLoop))))
556 return LegalStoreKind::None;
557
558 // Success. This store can be converted into a memcpy.
559 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
560 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
561 : LegalStoreKind::Memcpy;
562 }
563 // This store can't be transformed into a memset/memcpy.
564 return LegalStoreKind::None;
565}
566
567void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
568 StoreRefsForMemset.clear();
569 StoreRefsForMemsetPattern.clear();
570 StoreRefsForMemcpy.clear();
571 for (Instruction &I : *BB) {
573 if (!SI)
574 continue;
575
576 // Make sure this is a strided store with a constant stride.
577 switch (isLegalStore(SI)) {
578 case LegalStoreKind::None:
579 // Nothing to do
580 break;
581 case LegalStoreKind::Memset: {
582 // Find the base pointer.
583 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
584 StoreRefsForMemset[Ptr].push_back(SI);
585 } break;
586 case LegalStoreKind::MemsetPattern: {
587 // Find the base pointer.
588 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
589 StoreRefsForMemsetPattern[Ptr].push_back(SI);
590 } break;
591 case LegalStoreKind::Memcpy:
592 case LegalStoreKind::UnorderedAtomicMemcpy:
593 StoreRefsForMemcpy.push_back(SI);
594 break;
595 default:
596 assert(false && "unhandled return value");
597 break;
598 }
599 }
600}
601
602/// runOnLoopBlock - Process the specified block, which lives in a counted loop
603/// with the specified backedge count. This block is known to be in the current
604/// loop and not in any subloops.
605bool LoopIdiomRecognize::runOnLoopBlock(
606 BasicBlock *BB, const SCEV *BECount,
607 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
608 // We can only promote stores in this block if they are unconditionally
609 // executed in the loop. For a block to be unconditionally executed, it has
610 // to dominate all the exit blocks of the loop. Verify this now.
611 for (BasicBlock *ExitBlock : ExitBlocks)
612 if (!DT->dominates(BB, ExitBlock))
613 return false;
614
615 bool MadeChange = false;
616 // Look for store instructions, which may be optimized to memset/memcpy.
617 collectStores(BB);
618
619 // Look for a single store or sets of stores with a common base, which can be
620 // optimized into a memset (memset_pattern). The latter most commonly happens
621 // with structs and handunrolled loops.
622 for (auto &SL : StoreRefsForMemset)
623 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
624
625 for (auto &SL : StoreRefsForMemsetPattern)
626 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
627
628 // Optimize the store into a memcpy, if it feeds an similarly strided load.
629 for (auto &SI : StoreRefsForMemcpy)
630 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
631
632 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
633 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
634 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
635 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
636
637 return MadeChange;
638}
639
640/// See if this store(s) can be promoted to a memset.
641bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
642 const SCEV *BECount, ForMemset For) {
643 // Try to find consecutive stores that can be transformed into memsets.
644 SetVector<StoreInst *> Heads, Tails;
646
647 // Do a quadratic search on all of the given stores and find
648 // all of the pairs of stores that follow each other.
649 SmallVector<unsigned, 16> IndexQueue;
650 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
651 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
652
653 Value *FirstStoredVal = SL[i]->getValueOperand();
654 Value *FirstStorePtr = SL[i]->getPointerOperand();
655 const SCEVAddRecExpr *FirstStoreEv =
656 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
657 APInt FirstStride = getStoreStride(FirstStoreEv);
658 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
659
660 // See if we can optimize just this store in isolation.
661 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
662 Heads.insert(SL[i]);
663 continue;
664 }
665
666 Value *FirstSplatValue = nullptr;
667 Constant *FirstPatternValue = nullptr;
668
669 if (For == ForMemset::Yes)
670 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
671 else
672 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
673
674 assert((FirstSplatValue || FirstPatternValue) &&
675 "Expected either splat value or pattern value.");
676
677 IndexQueue.clear();
678 // If a store has multiple consecutive store candidates, search Stores
679 // array according to the sequence: from i+1 to e, then from i-1 to 0.
680 // This is because usually pairing with immediate succeeding or preceding
681 // candidate create the best chance to find memset opportunity.
682 unsigned j = 0;
683 for (j = i + 1; j < e; ++j)
684 IndexQueue.push_back(j);
685 for (j = i; j > 0; --j)
686 IndexQueue.push_back(j - 1);
687
688 for (auto &k : IndexQueue) {
689 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
690 Value *SecondStorePtr = SL[k]->getPointerOperand();
691 const SCEVAddRecExpr *SecondStoreEv =
692 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
693 APInt SecondStride = getStoreStride(SecondStoreEv);
694
695 if (FirstStride != SecondStride)
696 continue;
697
698 Value *SecondStoredVal = SL[k]->getValueOperand();
699 Value *SecondSplatValue = nullptr;
700 Constant *SecondPatternValue = nullptr;
701
702 if (For == ForMemset::Yes)
703 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
704 else
705 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
706
707 assert((SecondSplatValue || SecondPatternValue) &&
708 "Expected either splat value or pattern value.");
709
710 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
711 if (For == ForMemset::Yes) {
712 if (isa<UndefValue>(FirstSplatValue))
713 FirstSplatValue = SecondSplatValue;
714 if (FirstSplatValue != SecondSplatValue)
715 continue;
716 } else {
717 if (isa<UndefValue>(FirstPatternValue))
718 FirstPatternValue = SecondPatternValue;
719 if (FirstPatternValue != SecondPatternValue)
720 continue;
721 }
722 Tails.insert(SL[k]);
723 Heads.insert(SL[i]);
724 ConsecutiveChain[SL[i]] = SL[k];
725 break;
726 }
727 }
728 }
729
730 // We may run into multiple chains that merge into a single chain. We mark the
731 // stores that we transformed so that we don't visit the same store twice.
732 SmallPtrSet<Value *, 16> TransformedStores;
733 bool Changed = false;
734
735 // For stores that start but don't end a link in the chain:
736 for (StoreInst *I : Heads) {
737 if (Tails.count(I))
738 continue;
739
740 // We found a store instr that starts a chain. Now follow the chain and try
741 // to transform it.
742 SmallPtrSet<Instruction *, 8> AdjacentStores;
743 StoreInst *HeadStore = I;
744 unsigned StoreSize = 0;
745
746 // Collect the chain into a list.
747 while (Tails.count(I) || Heads.count(I)) {
748 if (TransformedStores.count(I))
749 break;
750 AdjacentStores.insert(I);
751
752 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
753 // Move to the next value in the chain.
754 I = ConsecutiveChain[I];
755 }
756
757 Value *StoredVal = HeadStore->getValueOperand();
758 Value *StorePtr = HeadStore->getPointerOperand();
759 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
760 APInt Stride = getStoreStride(StoreEv);
761
762 // Check to see if the stride matches the size of the stores. If so, then
763 // we know that every byte is touched in the loop.
764 if (StoreSize != Stride && StoreSize != -Stride)
765 continue;
766
767 bool IsNegStride = StoreSize == -Stride;
768
769 Type *IntIdxTy = DL->getIndexType(StorePtr->getType());
770 const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);
771 if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
772 MaybeAlign(HeadStore->getAlign()), StoredVal,
773 HeadStore, AdjacentStores, StoreEv, BECount,
774 IsNegStride)) {
775 TransformedStores.insert_range(AdjacentStores);
776 Changed = true;
777 }
778 }
779
780 return Changed;
781}
782
783/// processLoopMemIntrinsic - Template function for calling different processor
784/// functions based on mem intrinsic type.
785template <typename MemInst>
786bool LoopIdiomRecognize::processLoopMemIntrinsic(
787 BasicBlock *BB,
788 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
789 const SCEV *BECount) {
790 bool MadeChange = false;
791 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
792 Instruction *Inst = &*I++;
793 // Look for memory instructions, which may be optimized to a larger one.
794 if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
795 WeakTrackingVH InstPtr(&*I);
796 if (!(this->*Processor)(MI, BECount))
797 continue;
798 MadeChange = true;
799
800 // If processing the instruction invalidated our iterator, start over from
801 // the top of the block.
802 if (!InstPtr)
803 I = BB->begin();
804 }
805 }
806 return MadeChange;
807}
808
809/// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
810bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
811 const SCEV *BECount) {
812 // We can only handle non-volatile memcpys with a constant size.
813 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
814 return false;
815
816 // If we're not allowed to hack on memcpy, we fail. We don't mess with the
817 // inlined version as generating a larger inline mempcy could affect code
818 // size.
819 if (!HasMemcpy || MCI->isForceInlined() || DisableLIRP::Memcpy)
820 return false;
821
822 Value *Dest = MCI->getDest();
823 Value *Source = MCI->getSource();
824 if (!Dest || !Source)
825 return false;
826
827 // See if the load and store pointer expressions are AddRec like {base,+,1} on
828 // the current loop, which indicates a strided load and store. If we have
829 // something else, it's a random load or store we can't handle.
830 const SCEV *StoreEv = SE->getSCEV(Dest);
831 const SCEV *LoadEv = SE->getSCEV(Source);
832 const APInt *StoreStrideValue, *LoadStrideValue;
833 if (!match(StoreEv,
834 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(StoreStrideValue),
835 m_SpecificLoop(CurLoop))) ||
836 !match(LoadEv,
837 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(LoadStrideValue),
838 m_SpecificLoop(CurLoop))))
839 return false;
840
841 // Reject memcpys that are so large that they overflow an unsigned.
842 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
843 if ((SizeInBytes >> 32) != 0)
844 return false;
845
846 // Huge stride value - give up
847 if (StoreStrideValue->getBitWidth() > 64 ||
848 LoadStrideValue->getBitWidth() > 64)
849 return false;
850
851 if (SizeInBytes != *StoreStrideValue && SizeInBytes != -*StoreStrideValue) {
852 ORE.emit([&]() {
853 return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
854 << ore::NV("Inst", "memcpy") << " in "
855 << ore::NV("Function", MCI->getFunction())
856 << " function will not be hoisted: "
857 << ore::NV("Reason", "memcpy size is not equal to stride");
858 });
859 return false;
860 }
861
862 int64_t StoreStrideInt = StoreStrideValue->getSExtValue();
863 int64_t LoadStrideInt = LoadStrideValue->getSExtValue();
864 // Check if the load stride matches the store stride.
865 if (StoreStrideInt != LoadStrideInt)
866 return false;
867
868 return processLoopStoreOfLoopLoad(
869 Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),
870 MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI,
871 cast<SCEVAddRecExpr>(StoreEv), cast<SCEVAddRecExpr>(LoadEv), BECount);
872}
873
874/// processLoopMemSet - See if this memset can be promoted to a large memset.
875bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
876 const SCEV *BECount) {
877 // We can only handle non-volatile memsets.
878 if (MSI->isVolatile())
879 return false;
880
881 // If we're not allowed to hack on memset, we fail. We don't mess with the
882 // inlined version as generating a larger memset could affect code size.
883 if (!HasMemset || MSI->isForceInlined() || DisableLIRP::Memset)
884 return false;
885
886 Value *Pointer = MSI->getDest();
887
888 // See if the pointer expression is an AddRec like {base,+,1} on the current
889 // loop, which indicates a strided store. If we have something else, it's a
890 // random store we can't handle.
891 const SCEV *Ev = SE->getSCEV(Pointer);
892 const SCEV *PointerStrideSCEV;
893 if (!match(Ev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(PointerStrideSCEV),
894 m_SpecificLoop(CurLoop)))) {
895 LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n");
896 return false;
897 }
898
899 SCEVUse MemsetSizeSCEV = SE->getSCEV(MSI->getLength());
900
901 bool IsNegStride = false;
902 const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());
903
904 if (IsConstantSize) {
905 // Memset size is constant.
906 // Check if the pointer stride matches the memset size. If so, then
907 // we know that every byte is touched in the loop.
908 LLVM_DEBUG(dbgs() << " memset size is constant\n");
909 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
910 const APInt *Stride;
911 if (!match(PointerStrideSCEV, m_scev_APInt(Stride)))
912 return false;
913
914 if (SizeInBytes != *Stride && SizeInBytes != -*Stride)
915 return false;
916
917 IsNegStride = SizeInBytes == -*Stride;
918 } else {
919 // Memset size is non-constant.
920 // Check if the pointer stride matches the memset size.
921 // To be conservative, the pass would not promote pointers that aren't in
922 // address space zero. Also, the pass only handles memset length and stride
923 // that are invariant for the top level loop.
924 LLVM_DEBUG(dbgs() << " memset size is non-constant\n");
925 if (Pointer->getType()->getPointerAddressSpace() != 0) {
926 LLVM_DEBUG(dbgs() << " pointer is not in address space zero, "
927 << "abort\n");
928 return false;
929 }
930 if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {
931 LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, "
932 << "abort\n");
933 return false;
934 }
935
936 // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV
937 IsNegStride = PointerStrideSCEV->isNonConstantNegative();
938 SCEVUse PositiveStrideSCEV =
939 IsNegStride ? SCEVUse(SE->getNegativeSCEV(PointerStrideSCEV))
940 : SCEVUse(PointerStrideSCEV);
941 LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"
942 << " PositiveStrideSCEV: " << *PositiveStrideSCEV
943 << "\n");
944
945 if (PositiveStrideSCEV != MemsetSizeSCEV) {
946 // If an expression is covered by the loop guard, compare again and
947 // proceed with optimization if equal.
948 const SCEV *FoldedPositiveStride =
949 SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);
950 const SCEV *FoldedMemsetSize =
951 SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);
952
953 LLVM_DEBUG(dbgs() << " Try to fold SCEV based on loop guard\n"
954 << " FoldedMemsetSize: " << *FoldedMemsetSize << "\n"
955 << " FoldedPositiveStride: " << *FoldedPositiveStride
956 << "\n");
957
958 if (FoldedPositiveStride != FoldedMemsetSize) {
959 LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n");
960 return false;
961 }
962 }
963 }
964
965 // Verify that the memset value is loop invariant. If not, we can't promote
966 // the memset.
967 Value *SplatValue = MSI->getValue();
968 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
969 return false;
970
972 MSIs.insert(MSI);
973 return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
974 MSI->getDestAlign(), SplatValue, MSI, MSIs,
975 cast<SCEVAddRecExpr>(Ev), BECount, IsNegStride,
976 /*IsLoopMemset=*/true);
977}
978
979/// Return true if \p I is a (simple, loop-invariant-valued) store of the same
980/// bytewise value \p SplatByte.
981static bool isSameByteValueStore(Instruction &I, Value *SplatByte, Loop *L,
982 const DataLayout &DL) {
983 assert(SplatByte && "expected a bytewise splat value to match against");
984 auto *SI = dyn_cast<StoreInst>(&I);
985 if (!SI || !SI->isSimple() || !L->isLoopInvariant(SI->getValueOperand()))
986 return false;
987 return isBytewiseValue(SI->getValueOperand(), DL) == SplatByte;
988}
989
990/// mayLoopAccessLocation - Return true if the specified loop might access the
991/// specified pointer location, which is a loop-strided access. The 'Access'
992/// argument specifies what the verboten forms of access are (read or write).
993///
994/// When the access size cannot be bounded, fall back to allow stores writing
995/// the same byte value \p SplatByte.
997 const SCEV *BECount,
998 const SCEV *StoreSizeSCEV, AliasAnalysis &AA,
999 SmallPtrSetImpl<Instruction *> &IgnoredInsts,
1000 Value *SplatByte = nullptr,
1001 const DataLayout *DL = nullptr) {
1002 // Get the location that may be stored across the loop. Since the access is
1003 // strided positively through memory, we say that the modified location starts
1004 // at the pointer and has infinite size.
1006
1007 // If the loop iterates a fixed number of times, we can refine the access size
1008 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
1009 const APInt *BECst, *ConstSize;
1010 if (match(BECount, m_scev_APInt(BECst)) &&
1011 match(StoreSizeSCEV, m_scev_APInt(ConstSize))) {
1012 std::optional<uint64_t> BEInt = BECst->tryZExtValue();
1013 std::optional<uint64_t> SizeInt = ConstSize->tryZExtValue();
1014 // FIXME: Should this check for overflow?
1015 if (BEInt && SizeInt)
1016 AccessSize = LocationSize::precise((*BEInt + 1) * *SizeInt);
1017 }
1018
1019 // TODO: For this to be really effective, we have to dive into the pointer
1020 // operand in the store. Store to &A[i] of 100 will always return may alias
1021 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
1022 // which will then no-alias a store to &A[100].
1023 MemoryLocation StoreLoc(Ptr, AccessSize);
1024
1025 // Only consult the same-byte-value fallback when the access size stayed
1026 // infinite (non-constant trip count); with a precise size AA is accurate.
1027 bool TrySameByteValue = !AccessSize.isPrecise() && SplatByte && DL;
1028
1029 for (BasicBlock *B : L->blocks())
1030 for (Instruction &I : *B)
1031 if (!IgnoredInsts.contains(&I) &&
1032 isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access)) {
1033 if (TrySameByteValue && isSameByteValueStore(I, SplatByte, L, *DL))
1034 continue;
1035 return true;
1036 }
1037 return false;
1038}
1039
1040// If we have a negative stride, Start refers to the end of the memory location
1041// we're trying to memset. Therefore, we need to recompute the base pointer,
1042// which is just Start - BECount*Size.
1043static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
1044 Type *IntPtr, const SCEV *StoreSizeSCEV,
1045 ScalarEvolution *SE) {
1046 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1047 if (!StoreSizeSCEV->isOne()) {
1048 // index = back edge count * store size
1049 Index = SE->getMulExpr(Index,
1050 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1052 }
1053 // base pointer = start - index * store size
1054 return SE->getMinusSCEV(Start, Index);
1055}
1056
1057/// Compute the number of bytes as a SCEV from the backedge taken count.
1058///
1059/// This also maps the SCEV into the provided type and tries to handle the
1060/// computation in a way that will fold cleanly.
1061static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1062 const SCEV *StoreSizeSCEV, Loop *CurLoop,
1063 const DataLayout *DL, ScalarEvolution *SE) {
1064 const SCEV *TripCountSCEV =
1065 SE->getTripCountFromExitCount(BECount, IntPtr, CurLoop);
1066 return SE->getMulExpr(TripCountSCEV,
1067 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1069}
1070
1071/// processLoopStridedStore - We see a strided store of some value. If we can
1072/// transform this into a memset or memset_pattern in the loop preheader, do so.
1073bool LoopIdiomRecognize::processLoopStridedStore(
1074 Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
1075 Value *StoredVal, Instruction *TheStore,
1077 const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
1078 // We currently don't convert inline intrinsics into larger ones, to avoid
1079 // code size increase. `processLoopMemSet` checks that the intrinsic is not
1080 // inline before calling this function.
1081 assert((isa<StoreInst>(TheStore) ||
1082 !cast<MemIntrinsic>(TheStore)->isForceInlined()) &&
1083 "inline mem intrinsics should be filtered out by callers");
1084
1085 Module *M = TheStore->getModule();
1086
1087 // The trip count of the loop and the base pointer of the addrec SCEV is
1088 // guaranteed to be loop invariant, which means that it should dominate the
1089 // header. This allows us to insert code for it in the preheader.
1090 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1091 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1092 IRBuilder<> Builder(Preheader->getTerminator());
1093 SCEVExpander Expander(*SE, "loop-idiom");
1094 SCEVExpanderCleaner ExpCleaner(Expander);
1095
1096 Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1097 Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1098
1099 bool Changed = false;
1100 const SCEV *Start = Ev->getStart();
1101 // Handle negative strided loops.
1102 if (IsNegStride)
1103 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
1104
1105 // TODO: ideally we should still be able to generate memset if SCEV expander
1106 // is taught to generate the dependencies at the latest point.
1107 if (!Expander.isSafeToExpand(Start))
1108 return Changed;
1109
1110 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
1111 // this into a memset in the loop preheader now if we want. However, this
1112 // would be unsafe to do if there is anything else in the loop that may read
1113 // or write to the aliased location. Check for any overlap by generating the
1114 // base pointer and checking the region.
1115 Value *BasePtr =
1116 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1117
1118 // From here on out, conservatively report to the pass manager that we've
1119 // changed the IR, even if we later clean up these added instructions. There
1120 // may be structural differences e.g. in the order of use lists not accounted
1121 // for in just a textual dump of the IR. This is written as a variable, even
1122 // though statically all the places this dominates could be replaced with
1123 // 'true', with the hope that anyone trying to be clever / "more precise" with
1124 // the return value will read this comment, and leave them alone.
1125 Changed = true;
1126
1127 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1128 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1129 StoreSizeSCEV, *AA, Stores, SplatValue, DL))
1130 return Changed;
1131
1132 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1133 return Changed;
1134
1135 // Okay, everything looks good, insert the memset.
1136 Constant *PatternValue = nullptr;
1137 if (!SplatValue)
1138 PatternValue = getMemSetPatternValue(StoredVal, DL);
1139
1140 // MemsetArg is the number of bytes for the memset libcall, and the number
1141 // of pattern repetitions if the memset.pattern intrinsic is being used.
1142 Value *MemsetArg;
1143 std::optional<int64_t> BytesWritten;
1144
1145 if (PatternValue &&
1146 (HasMemsetPattern || Opts.loop_idiom_force_memset_pattern_intrinsic)) {
1147 const SCEV *TripCountS =
1148 SE->getTripCountFromExitCount(BECount, IntIdxTy, CurLoop);
1149 if (!Expander.isSafeToExpand(TripCountS))
1150 return Changed;
1151 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1152 if (!ConstStoreSize)
1153 return Changed;
1154 Value *TripCount = Expander.expandCodeFor(TripCountS, IntIdxTy,
1155 Preheader->getTerminator());
1156 uint64_t PatternRepsPerTrip =
1157 (ConstStoreSize->getValue()->getZExtValue() * 8) /
1158 DL->getTypeSizeInBits(PatternValue->getType());
1159 // If ConstStoreSize is not equal to the width of PatternValue, then
1160 // MemsetArg is TripCount * (ConstStoreSize/PatternValueWidth). Else
1161 // MemSetArg is just TripCount.
1162 MemsetArg =
1163 PatternRepsPerTrip == 1
1164 ? TripCount
1165 : Builder.CreateMul(TripCount,
1166 Builder.getIntN(IntIdxTy->getIntegerBitWidth(),
1167 PatternRepsPerTrip));
1168 if (auto *CI = dyn_cast<ConstantInt>(TripCount))
1169 BytesWritten =
1170 CI->getZExtValue() * ConstStoreSize->getValue()->getZExtValue();
1171
1172 } else {
1173 const SCEV *NumBytesS =
1174 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1175
1176 // TODO: ideally we should still be able to generate memset if SCEV expander
1177 // is taught to generate the dependencies at the latest point.
1178 if (!Expander.isSafeToExpand(NumBytesS))
1179 return Changed;
1180 MemsetArg =
1181 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1182 if (auto *CI = dyn_cast<ConstantInt>(MemsetArg))
1183 BytesWritten = CI->getZExtValue();
1184 }
1185 assert(MemsetArg && "MemsetArg should have been set");
1186
1187 AAMDNodes AATags = TheStore->getAAMetadata();
1188 for (Instruction *Store : Stores)
1189 AATags = AATags.merge(Store->getAAMetadata());
1190 if (BytesWritten)
1191 AATags = AATags.extendTo(BytesWritten.value());
1192 else
1193 AATags = AATags.extendTo(-1);
1194
1195 CallInst *NewCall;
1196 if (SplatValue) {
1197 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, MemsetArg,
1198 MaybeAlign(StoreAlignment),
1199 /*isVolatile=*/false, AATags);
1200 } else if (Opts.loop_idiom_force_memset_pattern_intrinsic ||
1201 isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16)) {
1202 assert(isa<SCEVConstant>(StoreSizeSCEV) && "Expected constant store size");
1203
1204 NewCall = Builder.CreateIntrinsicWithoutFolding(
1205 Intrinsic::experimental_memset_pattern,
1206 {DestInt8PtrTy, PatternValue->getType(), IntIdxTy},
1207 {BasePtr, PatternValue, MemsetArg,
1208 ConstantInt::getFalse(M->getContext())});
1209 if (StoreAlignment)
1210 cast<MemSetPatternInst>(NewCall)->setDestAlignment(*StoreAlignment);
1211 NewCall->setAAMetadata(AATags);
1212 } else {
1213 // Neither a memset, nor memset_pattern16
1214 return Changed;
1215 }
1216
1217 NewCall->setDebugLoc(TheStore->getDebugLoc());
1218
1219 if (MSSAU) {
1220 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1221 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1222 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1223 }
1224
1225 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
1226 << " from store to: " << *Ev << " at: " << *TheStore
1227 << "\n");
1228
1229 ORE.emit([&]() {
1230 OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",
1231 NewCall->getDebugLoc(), Preheader);
1232 R << "Transformed loop-strided store in "
1233 << ore::NV("Function", TheStore->getFunction())
1234 << " function into a call to "
1235 << ore::NV("NewFunction", NewCall->getCalledFunction())
1236 << "() intrinsic";
1237 if (!Stores.empty())
1238 R << ore::setExtraArgs();
1239 for (auto *I : Stores) {
1240 R << ore::NV("FromBlock", I->getParent()->getName())
1241 << ore::NV("ToBlock", Preheader->getName());
1242 }
1243 return R;
1244 });
1245
1246 // Okay, the memset has been formed. Zap the original store and anything that
1247 // feeds into it.
1248 for (auto *I : Stores) {
1249 if (MSSAU)
1250 MSSAU->removeMemoryAccess(I, true);
1252 }
1253 if (MSSAU && VerifyMemorySSA)
1254 MSSAU->getMemorySSA()->verifyMemorySSA();
1255 ++NumMemSet;
1256 ExpCleaner.markResultUsed();
1257 return true;
1258}
1259
1260/// If the stored value is a strided load in the same loop with the same stride
1261/// this may be transformable into a memcpy. This kicks in for stuff like
1262/// for (i) A[i] = B[i];
1263bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1264 const SCEV *BECount) {
1265 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
1266
1267 Value *StorePtr = SI->getPointerOperand();
1268 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1269 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1270
1271 // The store must be feeding a non-volatile load.
1272 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1273 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
1274
1275 // See if the pointer expression is an AddRec like {base,+,1} on the current
1276 // loop, which indicates a strided load. If we have something else, it's a
1277 // random load we can't handle.
1278 Value *LoadPtr = LI->getPointerOperand();
1279 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1280
1281 const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);
1282 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1283 SI->getAlign(), LI->getAlign(), SI, LI,
1284 StoreEv, LoadEv, BECount);
1285}
1286
1287namespace {
1288class MemmoveVerifier {
1289public:
1290 explicit MemmoveVerifier(const SCEV &LoadStart, const SCEV &StoreStart,
1291 ScalarEvolution &SE)
1292 : DL(SE.getDataLayout()),
1293 Off(dyn_cast<SCEVConstant>(SE.getMinusSCEV(&StoreStart, &LoadStart))),
1294 BasePtr(dyn_cast<SCEVUnknown>(SE.getPointerBase(&StoreStart))),
1295 IsSameObject(Off != nullptr) {}
1296
1297 bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,
1298 const Instruction &TheLoad,
1299 bool IsMemCpy) const {
1300 // The store must be at a constant offset from the load, and there must be
1301 // an underlying pointer.
1302 if (!Off || !BasePtr)
1303 return false;
1304 const APInt &OffVal = Off->getAPInt();
1305 // If null is defined then the base pointer can't be null
1306 auto *NullBase = dyn_cast<ConstantPointerNull>(BasePtr->getValue());
1307 if (NullBase && NullPointerIsDefined(
1308 TheLoad.getParent()->getParent(),
1309 NullBase->getPointerType()->getPointerAddressSpace()))
1310 return false;
1311 int64_t LoadSize;
1312 if (IsMemCpy) {
1313 // memcpy is equivalent to a sequence of byte loads and stores
1314 LoadSize = 1;
1315 } else {
1316 LoadSize = DL.getTypeSizeInBits(TheLoad.getType()).getFixedValue() / 8;
1317 if (LoadSize != StoreSize)
1318 return false;
1319 }
1320 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1321 // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1322 if (IsNegStride ? OffVal.slt(LoadSize) : OffVal.sgt(-LoadSize))
1323 return false;
1324 return true;
1325 }
1326
1327private:
1328 const DataLayout &DL;
1329 const SCEVConstant *Off;
1330 const SCEVUnknown *BasePtr;
1331
1332public:
1333 const bool IsSameObject;
1334};
1335} // namespace
1336
1337bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1338 Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,
1339 MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,
1340 Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,
1341 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
1342 // We currently don't convert inline intrinsics into larger ones, to avoid
1343 // code size increase. `processLoopMemCpy` checks that the intrinsic is not
1344 // inline before calling this function.
1345 assert((isa<StoreInst>(TheStore) ||
1346 !cast<MemIntrinsic>(TheStore)->isForceInlined()) &&
1347 "inline mem intrinsics should be filtered out by callers");
1348
1349 // The trip count of the loop and the base pointer of the addrec SCEV is
1350 // guaranteed to be loop invariant, which means that it should dominate the
1351 // header. This allows us to insert code for it in the preheader.
1352 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1353 IRBuilder<> Builder(Preheader->getTerminator());
1354 SCEVExpander Expander(*SE, "loop-idiom");
1355
1356 SCEVExpanderCleaner ExpCleaner(Expander);
1357
1358 bool Changed = false;
1359 const SCEV *StrStart = StoreEv->getStart();
1360 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1361 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1362
1363 APInt Stride = getStoreStride(StoreEv);
1364 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1365
1366 // TODO: Deal with non-constant size; Currently expect constant store size
1367 assert(ConstStoreSize && "store size is expected to be a constant");
1368
1369 int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();
1370 bool IsNegStride = StoreSize == -Stride;
1371
1372 // Handle negative strided loops.
1373 if (IsNegStride)
1374 StrStart =
1375 getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1376
1377 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1378 // this into a memcpy in the loop preheader now if we want. However, this
1379 // would be unsafe to do if there is anything else in the loop that may read
1380 // or write the memory region we're storing to. This includes the load that
1381 // feeds the stores. Check for an alias by generating the base address and
1382 // checking everything.
1383 Value *StoreBasePtr = Expander.expandCodeFor(
1384 StrStart, Builder.getPtrTy(StrAS), Preheader->getTerminator());
1385
1386 // From here on out, conservatively report to the pass manager that we've
1387 // changed the IR, even if we later clean up these added instructions. There
1388 // may be structural differences e.g. in the order of use lists not accounted
1389 // for in just a textual dump of the IR. This is written as a variable, even
1390 // though statically all the places this dominates could be replaced with
1391 // 'true', with the hope that anyone trying to be clever / "more precise" with
1392 // the return value will read this comment, and leave them alone.
1393 Changed = true;
1394
1395 SmallPtrSet<Instruction *, 2> IgnoredInsts;
1396 IgnoredInsts.insert(TheStore);
1397
1398 bool IsMemCpy = isa<MemCpyInst>(TheStore);
1399 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1400
1401 bool LoopAccessStore =
1402 mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1403 StoreSizeSCEV, *AA, IgnoredInsts);
1404 if (LoopAccessStore) {
1405 // For memmove case it's not enough to guarantee that loop doesn't access
1406 // TheStore and TheLoad. Additionally we need to make sure that TheStore is
1407 // the only user of TheLoad.
1408 if (!TheLoad->hasOneUse())
1409 return Changed;
1410 IgnoredInsts.insert(TheLoad);
1411 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1412 BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1413 ORE.emit([&]() {
1414 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1415 TheStore)
1416 << ore::NV("Inst", InstRemark) << " in "
1417 << ore::NV("Function", TheStore->getFunction())
1418 << " function will not be hoisted: "
1419 << ore::NV("Reason", "The loop may access store location");
1420 });
1421 return Changed;
1422 }
1423 IgnoredInsts.erase(TheLoad);
1424 }
1425
1426 const SCEV *LdStart = LoadEv->getStart();
1427 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1428
1429 // Handle negative strided loops.
1430 if (IsNegStride)
1431 LdStart =
1432 getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1433
1434 // For a memcpy, we have to make sure that the input array is not being
1435 // mutated by the loop.
1436 Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
1437 Preheader->getTerminator());
1438
1439 // If the store is a memcpy instruction, we must check if it will write to
1440 // the load memory locations. So remove it from the ignored stores.
1441 MemmoveVerifier Verifier(*LdStart, *StrStart, *SE);
1442 if (IsMemCpy && !Verifier.IsSameObject)
1443 IgnoredInsts.erase(TheStore);
1444 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1445 StoreSizeSCEV, *AA, IgnoredInsts)) {
1446 ORE.emit([&]() {
1447 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1448 << ore::NV("Inst", InstRemark) << " in "
1449 << ore::NV("Function", TheStore->getFunction())
1450 << " function will not be hoisted: "
1451 << ore::NV("Reason", "The loop may access load location");
1452 });
1453 return Changed;
1454 }
1455
1456 bool IsAtomic = TheStore->isAtomic() || TheLoad->isAtomic();
1457 bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;
1458
1459 if (IsAtomic) {
1460 // For now don't support unordered atomic memmove.
1461 if (UseMemMove)
1462 return Changed;
1463
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 && LoadAlign) &&
1467 "Expect unordered load/store to have align.");
1468 if (*StoreAlign < StoreSize || *LoadAlign < 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
1479 if (UseMemMove)
1480 if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1481 IsMemCpy))
1482 return Changed;
1483
1484 if (avoidLIRForMultiBlockLoop())
1485 return Changed;
1486
1487 // Okay, everything is safe, we can transform this!
1488
1489 const SCEV *NumBytesS =
1490 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1491
1492 Value *NumBytes =
1493 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1494
1495 AAMDNodes AATags = TheLoad->getAAMetadata();
1496 AAMDNodes StoreAATags = TheStore->getAAMetadata();
1497 AATags = AATags.merge(StoreAATags);
1498 if (auto CI = dyn_cast<ConstantInt>(NumBytes))
1499 AATags = AATags.extendTo(CI->getZExtValue());
1500 else
1501 AATags = AATags.extendTo(-1);
1502
1503 CallInst *NewCall = nullptr;
1504 // Check whether to generate an unordered atomic memcpy:
1505 // If the load or store are atomic, then they must necessarily be unordered
1506 // by previous checks.
1507 if (!IsAtomic) {
1508 if (UseMemMove)
1509 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr,
1510 LoadAlign, NumBytes,
1511 /*isVolatile=*/false, AATags);
1512 else
1513 NewCall =
1514 Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1515 NumBytes, /*isVolatile=*/false, AATags);
1516 } else {
1517 // Create the call.
1518 // Note that unordered atomic loads/stores are *required* by the spec to
1519 // have an alignment but non-atomic loads/stores may not.
1520 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1521 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1522 AATags);
1523 }
1524 NewCall->setDebugLoc(TheStore->getDebugLoc());
1525
1526 if (MSSAU) {
1527 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1528 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1529 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1530 }
1531
1532 LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n"
1533 << " from load ptr=" << *LoadEv << " at: " << *TheLoad
1534 << "\n"
1535 << " from store ptr=" << *StoreEv << " at: " << *TheStore
1536 << "\n");
1537
1538 ORE.emit([&]() {
1539 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1540 NewCall->getDebugLoc(), Preheader)
1541 << "Formed a call to "
1542 << ore::NV("NewFunction", NewCall->getCalledFunction())
1543 << "() intrinsic from " << ore::NV("Inst", InstRemark)
1544 << " instruction in " << ore::NV("Function", TheStore->getFunction())
1545 << " function"
1547 << ore::NV("FromBlock", TheStore->getParent()->getName())
1548 << ore::NV("ToBlock", Preheader->getName());
1549 });
1550
1551 // Okay, a new call to memcpy/memmove has been formed. Zap the original store
1552 // and anything that feeds into it.
1553 if (MSSAU)
1554 MSSAU->removeMemoryAccess(TheStore, true);
1555 deleteDeadInstruction(TheStore);
1556 if (MSSAU && VerifyMemorySSA)
1557 MSSAU->getMemorySSA()->verifyMemorySSA();
1558 if (UseMemMove)
1559 ++NumMemMove;
1560 else
1561 ++NumMemCpy;
1562 ExpCleaner.markResultUsed();
1563 return true;
1564}
1565
1566// When compiling for codesize we avoid idiom recognition for a multi-block loop
1567// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1568//
1569bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1570 bool IsLoopMemset) {
1571 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1572 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1573 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1574 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1575 << " avoided: multi-block top-level loop\n");
1576 return true;
1577 }
1578 }
1579
1580 return false;
1581}
1582
1583bool LoopIdiomRecognize::optimizeCRCLoop(const PolynomialInfo &Info) {
1584 // FIXME: Hexagon has a special HexagonLoopIdiom that optimizes CRC using
1585 // carry-less multiplication instructions, which is more efficient than our
1586 // Sarwate table-lookup optimization. Hence, until we're able to emit
1587 // target-specific instructions for Hexagon, subsuming HexagonLoopIdiom,
1588 // disable the optimization for Hexagon.
1589 Module &M = *CurLoop->getHeader()->getModule();
1590 Triple TT(M.getTargetTriple());
1591 if (TT.getArch() == Triple::hexagon)
1592 return false;
1593
1594 LLVMContext &Ctx = Info.LHS->getContext();
1595 Type *CRCTy = Info.LHS->getType();
1596 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1597
1598 // CRC computation is mostly serial, so latency works best for comparison.
1601
1602 InstructionCost XorCost =
1603 TTI->getArithmeticInstrCost(Instruction::Xor, CRCTy, CostKind);
1604 InstructionCost ShiftCost =
1605 TTI->getArithmeticInstrCost(Instruction::LShr, CRCTy, CostKind);
1606 InstructionCost AndCost =
1607 TTI->getArithmeticInstrCost(Instruction::And, CRCTy, CostKind);
1608 InstructionCost SelectCost =
1609 TTI->getCmpSelInstrCost(Instruction::Select, CRCTy, Type::getInt1Ty(Ctx),
1611 InstructionCost LoadCost =
1612 TTI->getMemoryOpCost(Instruction::Load, CRCTy, DL->getABITypeAlign(CRCTy),
1613 DL->getDefaultGlobalsAddressSpace(), CostKind);
1614 auto ClmulCost = [&](unsigned BW) {
1615 auto *Ty = IntegerType::get(Ctx, BW);
1616 IntrinsicCostAttributes Attrs(Intrinsic::clmul, Ty, {Ty, Ty});
1617 return TTI->getIntrinsicInstrCost(Attrs, CostKind);
1618 };
1619
1620 // Estimate the cost of the original, unoptimized loop.
1621 InstructionCost OrigLoopCost =
1622 (2 * ShiftCost + 2 * XorCost + AndCost + SelectCost) * Info.TripCount;
1623
1624 // Estimate the cost of the Sarwate lookup table optimization strategy.
1625 // As mentioned previously, a byte-multiple trip count is required.
1626 InstructionCost TableStrategyCost =
1627 Info.TripCount % 8 != 0
1629 : (LoadCost + XorCost + 2 * ShiftCost) * (Info.TripCount / 8);
1630
1631 // Estimate the cost of the carry-less multiplication optimization strategy.
1632 InstructionCost ClmulStrategyCost = ClmulCost(2 * Info.TripCount) +
1633 ClmulCost(CRCBW + Info.TripCount) +
1634 2 * XorCost + 2 * ShiftCost + AndCost;
1635
1636 ORE.emit([&]() {
1637 return OptimizationRemarkAnalysis(DEBUG_TYPE, "CRCLoopCosts",
1638 CurLoop->getStartLoc(),
1639 CurLoop->getHeader())
1640 << "CRC loop costs: original="
1641 << ore::NV("OrigLoopCost", OrigLoopCost)
1642 << ", table=" << ore::NV("TableStrategyCost", TableStrategyCost)
1643 << ", clmul=" << ore::NV("ClmulStrategyCost", ClmulStrategyCost);
1644 });
1645
1646 auto ReportMissed = [&](StringRef Reason) {
1647 ORE.emit([&]() {
1648 return OptimizationRemarkMissed(DEBUG_TYPE, "CRCLoopMissed",
1649 CurLoop->getStartLoc(),
1650 CurLoop->getHeader())
1651 << "CRC loop not optimized: " << Reason;
1652 });
1653 };
1654 auto ReportOptimized = [&](StringRef Strategy, StringRef Reason) {
1655 ORE.emit([&]() {
1656 return OptimizationRemark(DEBUG_TYPE, "CRCLoopOptimized",
1657 CurLoop->getStartLoc(), CurLoop->getHeader())
1658 << "CRC loop optimized using " << ore::NV("Strategy", Strategy)
1659 << ": " << Reason;
1660 });
1661 };
1662
1663 switch (Opts.loop_idiom_crc_strategy) {
1664 default:
1665 ReportMissed("disabled by user");
1666 return false;
1668 // The table strategy is not possible in its current form without a byte-
1669 // multiple trip count.
1670 if (Info.TripCount % 8 == 0) {
1671 optimizeCRCLoopUsingTableLookup(Info);
1672 ReportOptimized("table", "forced by user");
1673 return true;
1674 }
1675 ReportMissed("table strategy forced, but not possible");
1676 return false;
1678 optimizeCRCLoopUsingClmul(Info);
1679 ReportOptimized("clmul", "forced by user");
1680 return true;
1682 // When using the auto strategy, bail if we are optimizing for size since
1683 // there's usually not a clear size benefit.
1684 // TODO: The clmul optimization is around the same size in many cases, so it
1685 // could be worth it to take advantage of that fact, especially if it would
1686 // be much faster than the original loop.
1687 if (ApplyCodeSizeHeuristics) {
1688 ReportMissed("optimizing for size");
1689 return false;
1690 }
1691
1692 // Only apply an optimization if there's a clear benefit to doing so.
1693 if (std::min(TableStrategyCost, ClmulStrategyCost) >= OrigLoopCost) {
1694 ReportMissed("no profitable strategy");
1695 return false;
1696 }
1697
1698 if (TableStrategyCost <= ClmulStrategyCost) {
1699 optimizeCRCLoopUsingTableLookup(Info);
1700 ReportOptimized("table", "most profitable strategy");
1701 } else {
1702 optimizeCRCLoopUsingClmul(Info);
1703 ReportOptimized("clmul", "most profitable strategy");
1704 }
1705 return true;
1706 }
1707}
1708
1709// The algorithm used in this optimization is a Polynomial (GF(2)) Barrett
1710// Reduction based on Intel's "Fast CRC Computation for Generic Polynomials
1711// Using PCLMULQDQ Instruction" white paper (December 2009).
1712void LoopIdiomRecognize::optimizeCRCLoopUsingClmul(const PolynomialInfo &Info) {
1713 // TODO: If clmul exists on the target but not for the required width, it
1714 // might be possible to split into multiple iterations of reduction.
1715 Type *CRCTy = Info.LHS->getType();
1716 LLVMContext &Ctx = CRCTy->getContext();
1717 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1718 // The loop's TripCount determines how many bits of the data are processed,
1719 // regardless of whether the actual data bit width matches (if auxiliary data
1720 // is even used at all).
1721 unsigned TC = Info.TripCount;
1722 // Based on the clmul inputs, the first clmul needs 2*TC bits, and the second
1723 // needs CRCBW+TC bits. However, only the low TC bits of the first clmul are
1724 // used in little-endian, so a clmul in TC bits suffices in that case.
1725 IntegerType *ClmulMuTy =
1726 IntegerType::get(Ctx, Info.IsBigEndian ? 2 * TC : TC);
1727 IntegerType *ClmulGPTy = IntegerType::get(Ctx, CRCBW + TC);
1728
1729 // First, generate the constants required for GF(2) Barrett reduction.
1730 auto [Mu, FullGenPoly] = HashRecognize::genBarrettConstants(Info);
1731 Value *MuConst =
1732 ConstantInt::get(Ctx, Mu.zextOrTrunc(ClmulMuTy->getBitWidth()));
1733 Value *GenPolyConst =
1734 ConstantInt::get(Ctx, FullGenPoly.zext(ClmulGPTy->getBitWidth()));
1735
1736 IRBuilder<> Builder(CurLoop->getLoopPreheader()->getTerminator());
1737
1738 // If a shift needs to occur in the setup for the first clmul with MuConst, it
1739 // will be by abs(TC - CRCBW). To ensure that the shift can work without
1740 // losing information or creating poison, give it CRCBW + TC bits.
1741 bool SetupShiftNeeded = Info.IsBigEndian && TC != CRCBW;
1742 auto *SetupTy = IntegerType::get(Ctx, SetupShiftNeeded ? CRCBW + TC : TC);
1743
1744 // Based on the Intel white paper, in our case, we have
1745 // R(x) = (LHS*x^TC) xor (LHSAux ? getTCBits(LHSAux)*x^CRCBW : 0)
1746 // since the CRC loop multiplies LHS by x each iteration, and the x^CRCBW term
1747 // of getTCBits(LHSAux) is XORed in for the significant bit check.
1748 // Rather than compute the full R(x), we can split it in two: a quotient for
1749 // step 1 (floor(R(x)/x^CRCBW)) and a remainder for step 3 (R(x) mod x^CRCBW).
1750 //
1751 // ClmulMuInput is an evolving variable that will eventually become the part
1752 // used in step 1, which can be simplified to
1753 // (LHS*x^(TC-CRCBW)) xor (LHSAux ? getTCBits(LHSAux) : 0).
1754 // Thanks to restrictions imposed by HashRecognize for big-endian CRC loops,
1755 // getTCBits(LHSAux) = LHSAux*x^(TC-CRCBW), so this can be further simplified
1756 // to (LHS xor (LHSAux ? LHSAux : 0))*x^(TC-CRCBW).
1757 Value *ClmulMuInput =
1758 Builder.CreateZExtOrTrunc(Info.LHS, SetupTy, "crc.cast");
1759
1760 // If auxiliary data is present, XOR it in with the CRC.
1761 if (Value *Data = Info.LHSAux) {
1762 // This is usually a zext, but DataBW may exceed CRCBW+TC if both CRCBW and
1763 // TC are small enough.
1764 Data = Builder.CreateZExtOrTrunc(Data, SetupTy, "data.cast");
1765
1766 ClmulMuInput = Builder.CreateXor(ClmulMuInput, Data, "xor.crc.data");
1767 }
1768
1769 // Align the current CRC with TripCount (multiply or divide by x^(TC-CRCBW)).
1770 if (SetupShiftNeeded) {
1771 ClmulMuInput =
1772 TC > CRCBW
1773 ? Builder.CreateShl(ClmulMuInput, TC - CRCBW, "crc.align.tc")
1774 : Builder.CreateLShr(ClmulMuInput, CRCBW - TC, "crc.align.tc");
1775 }
1776
1777 // Zero out any bits above (TC-1) for calculation since the original loop
1778 // doesn't use them in the significant bit checks.
1779 if (SetupTy->getBitWidth() > TC) {
1780 auto *Mask =
1781 ConstantInt::get(Ctx, APInt::getLowBitsSet(SetupTy->getBitWidth(), TC));
1782 ClmulMuInput = Builder.CreateAnd(ClmulMuInput, Mask, "crc.tcbits");
1783 }
1784
1785 // Step 1: T1(x) = floor(R(x)/x^CRCBW) * mu
1786 // Input is TC bits and mu is TC+1 bits, so result will be 2*TC bits.
1787 ClmulMuInput =
1788 Builder.CreateZExtOrTrunc(ClmulMuInput, ClmulMuTy, "tcbits.cast");
1789 Value *ClmulMu = Builder.CreateBinaryIntrinsic(
1790 Intrinsic::clmul, ClmulMuInput, MuConst, /*FMFSource=*/{}, "clmul.mu");
1791
1792 // Calculate floor(T1(x)/x^TC) for step 2.
1793 Value *ClmulGPInput =
1794 Info.IsBigEndian ? Builder.CreateLShr(ClmulMu, TC, "quot.lshr") : ClmulMu;
1795
1796 // Step 2: T2(x) = floor(T1(x)/x^TC) * P(x)
1797 // Input is TC bits and P(x) is CRCBW+1 bits, so result will be CRCBW+TC bits.
1798 ClmulGPInput =
1799 Builder.CreateZExtOrTrunc(ClmulGPInput, ClmulGPTy, "quot.cast");
1800 Value *ClmulGP = Builder.CreateBinaryIntrinsic(Intrinsic::clmul, ClmulGPInput,
1801 GenPolyConst,
1802 /*FMFSource=*/{}, "clmul.gp");
1803
1804 // Calculate the least significant part of R(x) for step 3 as specified above.
1805 // R(x) mod x^CRCBW = LHS*x^TC mod x^CRCBW, though the (mod x^CRCBW) is
1806 // handled later on when truncating back to CRCBW for ComputedValue.
1807 Value *CRCNext = Builder.CreateZExt(Info.LHS, ClmulGPTy, "crc.recast");
1808 if (Info.IsBigEndian)
1809 CRCNext = Builder.CreateShl(CRCNext, TC, "crc.shl");
1810
1811 // Step 3: C(x) = (R(x) xor T2(x)) mod x^CRCBW
1812 CRCNext = Builder.CreateXor(CRCNext, ClmulGP, "xor.crc.mult");
1813 if (!Info.IsBigEndian)
1814 CRCNext = Builder.CreateLShr(CRCNext, TC, "crc.lshr");
1815
1816 // Bring the result back down the the CRC bit width.
1817 CRCNext = Builder.CreateTrunc(CRCNext, CRCTy, "crc.next");
1818
1819 // Replace the result of the loop with the new computed CRC value.
1820 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext, CurLoop->getLoopLatch());
1821
1822 // Finally, clean up the loop as much as possible so it can be trivially
1823 // deleted.
1824 {
1825 for (PHINode &PN : make_early_inc_range(CurLoop->getHeader()->phis())) {
1826 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1828 }
1829 // Replace the exit condition with constant true/false to always cause a
1830 // branch to the exit block.
1832 auto *BrInst = cast<CondBrInst>(CurLoop->getLoopLatch()->getTerminator());
1833 BrInst->setCondition(ConstantInt::getBool(
1834 Ctx, BrInst->getSuccessor(0) == CurLoop->getExitBlock()));
1835 SE->forgetLoop(CurLoop);
1836 }
1837}
1838
1839void LoopIdiomRecognize::optimizeCRCLoopUsingTableLookup(
1840 const PolynomialInfo &Info) {
1841 assert(Info.TripCount % 8 == 0 && "A byte-multiple trip count is required");
1842
1843 // First, create a new GlobalVariable corresponding to the
1844 // Sarwate-lookup-table.
1845 Type *CRCTy = Info.LHS->getType();
1846 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1847 std::array<Constant *, 256> CRCConstants;
1849 CRCConstants.begin(),
1850 [CRCTy](const APInt &E) { return ConstantInt::get(CRCTy, E); });
1851 Constant *ConstArray =
1852 ConstantArray::get(ArrayType::get(CRCTy, 256), CRCConstants);
1854 *CurLoop->getHeader()->getModule(), ConstArray->getType(), true,
1855 GlobalValue::PrivateLinkage, ConstArray, ".crctable");
1856
1859
1860 // Next, mark all PHIs for removal except IV.
1861 {
1862 for (PHINode &PN : CurLoop->getHeader()->phis()) {
1863 if (&PN == IV)
1864 continue;
1865 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1866 Cleanup.push_back(&PN);
1867 }
1868 }
1869
1870 // Next, fix up the trip count.
1871 {
1872 unsigned NewBTC = (Info.TripCount / 8) - 1;
1873 BasicBlock *LoopBlk = CurLoop->getLoopLatch();
1874 CondBrInst *BrInst = cast<CondBrInst>(LoopBlk->getTerminator());
1875 CmpPredicate ExitPred = BrInst->getSuccessor(0) == LoopBlk
1878 Instruction *ExitCond = CurLoop->getLatchCmpInst();
1879 Value *ExitLimit = ConstantInt::get(IV->getType(), NewBTC);
1880 IRBuilder<> Builder(ExitCond);
1881 Value *NewExitCond =
1882 Builder.CreateICmp(ExitPred, IV, ExitLimit, "exit.cond");
1883 ExitCond->replaceAllUsesWith(NewExitCond);
1884 deleteDeadInstruction(ExitCond);
1885 }
1886
1887 // Finally, fill the loop with the Sarwate-table-lookup logic, and replace all
1888 // uses of ComputedValue.
1889 //
1890 // Little-endian:
1891 // crc = (crc >> 8) ^ tbl[(iv'th byte of data) ^ (bottom byte of crc)]
1892 // Big-Endian:
1893 // crc = (crc << 8) ^ tbl[(iv'th byte of data) ^ (top byte of crc)]
1894 {
1895 auto LoByte = [](IRBuilderBase &Builder, Value *Op, const Twine &Name) {
1896 return Builder.CreateZExtOrTrunc(
1897 Op, IntegerType::getInt8Ty(Op->getContext()), Name);
1898 };
1899 auto HiIdx = [LoByte, CRCBW](IRBuilderBase &Builder, Value *Op,
1900 const Twine &Name) {
1901 // Shift the top bits of Op to the bottom byte by using the CRC bitwidth
1902 // as a reference.
1903 if (CRCBW != 8) {
1904 Op = CRCBW > 8 ? Builder.CreateLShr(Op, CRCBW - 8, Name)
1905 : Builder.CreateShl(Op, 8 - CRCBW, Name);
1906 }
1907 return LoByte(Builder, Op, Name + ".lo.byte");
1908 };
1909
1910 IRBuilder<> Builder(CurLoop->getHeader()->getFirstNonPHIIt());
1911
1912 // Create the CRC PHI, and initialize its incoming value to the initial
1913 // value of CRC.
1914 PHINode *CRCPhi = Builder.CreatePHI(CRCTy, 2, "crc");
1915 CRCPhi->addIncoming(Info.LHS, CurLoop->getLoopPreheader());
1916
1917 // CRC is now an evolving variable, initialized to the PHI.
1918 Value *CRC = CRCPhi;
1919
1920 // TableIndexer = ((top|bottom) byte of CRC). It is XOR'ed with (iv'th byte
1921 // of LHSAux), if LHSAux is non-nullptr.
1922 Value *Indexer = CRC;
1923 if (Value *Data = Info.LHSAux) {
1924 Type *DataTy = Data->getType();
1925
1926 // To index into the (iv'th byte of LHSAux), we multiply iv by 8, and we
1927 // shift right by that amount, and take the lo-byte (in the little-endian
1928 // case), or shift left by that amount, and take the hi-idx (in the
1929 // big-endian case).
1930 Value *IVBits = Builder.CreateZExtOrTrunc(
1931 Builder.CreateShl(IV, 3, "iv.bits"), DataTy, "iv.indexer");
1932 Value *DataIndexer =
1933 Info.IsBigEndian ? Builder.CreateShl(Data, IVBits, "data.indexer")
1934 : Builder.CreateLShr(Data, IVBits, "data.indexer");
1935 Indexer = Builder.CreateXor(
1936 DataIndexer,
1937 Builder.CreateZExtOrTrunc(Indexer, DataTy, "crc.indexer.cast"),
1938 "crc.data.indexer");
1939 }
1940
1941 Indexer = Info.IsBigEndian ? HiIdx(Builder, Indexer, "indexer.hi")
1942 : LoByte(Builder, Indexer, "indexer.lo");
1943
1944 // Always index into a GEP using the index type.
1945 Indexer = Builder.CreateZExt(
1946 Indexer, SE->getDataLayout().getIndexType(GV->getType()),
1947 "indexer.ext");
1948
1949 // CRCTableLd = CRCTable[(iv'th byte of data) ^ (top|bottom) byte of CRC].
1950 Value *CRCTableGEP =
1951 Builder.CreateInBoundsGEP(CRCTy, GV, Indexer, "tbl.ptradd");
1952 Instruction *CRCTableLd = Builder.CreateLoad(CRCTy, CRCTableGEP, "tbl.ld");
1953
1954 // Update MemorySSA since we just created a new load instruction.
1955 if (MSSAU) {
1956 auto *NewMemAcc = MSSAU->createMemoryAccessInBB(
1957 CRCTableLd, /*Definition=*/nullptr, CRCTableLd->getParent(),
1959 MSSAU->insertUse(cast<MemoryUse>(NewMemAcc), /*RenameUses=*/true);
1960 }
1961
1962 // CRCNext = (CRC (<<|>>) 8) ^ CRCTableLd, or simply CRCTableLd in case of
1963 // CRC-8.
1964 Value *CRCNext = CRCTableLd;
1965 if (CRCBW > 8) {
1966 Value *CRCShift = Info.IsBigEndian
1967 ? Builder.CreateShl(CRC, 8, "crc.be.shift")
1968 : Builder.CreateLShr(CRC, 8, "crc.le.shift");
1969 CRCNext = Builder.CreateXor(CRCShift, CRCTableLd, "crc.next");
1970 }
1971
1972 // Connect the back-edge for the loop, and RAUW the ComputedValue.
1973 CRCPhi->addIncoming(CRCNext, CurLoop->getLoopLatch());
1974 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext,
1975 CurLoop->getLoopLatch());
1976 }
1977
1978 // Cleanup.
1979 {
1980 for (PHINode *PN : Cleanup)
1982 SE->forgetLoop(CurLoop);
1983 if (MSSAU && VerifyMemorySSA)
1984 MSSAU->getMemorySSA()->verifyMemorySSA();
1985 }
1986}
1987
1988bool LoopIdiomRecognize::runOnNoncountableLoop() {
1989 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1990 << CurLoop->getHeader()->getParent()->getName()
1991 << "] Noncountable Loop %"
1992 << CurLoop->getHeader()->getName() << "\n");
1993
1994 return recognizePopcount() || recognizeAndInsertFFS() ||
1995 recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||
1996 recognizeShiftUntilLessThan() || recognizeAndInsertStrLen();
1997}
1998
1999/// Check if the given conditional branch is based on the comparison between
2000/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
2001/// true), the control yields to the loop entry. If the branch matches the
2002/// behavior, the variable involved in the comparison is returned. This function
2003/// will be called to see if the precondition and postcondition of the loop are
2004/// in desirable form.
2006 bool JmpOnZero = false) {
2008 if (!Cond)
2009 return nullptr;
2010
2011 auto *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
2012 if (!CmpZero || !CmpZero->isZero())
2013 return nullptr;
2014
2015 BasicBlock *TrueSucc = BI->getSuccessor(0);
2016 BasicBlock *FalseSucc = BI->getSuccessor(1);
2017 if (JmpOnZero)
2018 std::swap(TrueSucc, FalseSucc);
2019
2020 ICmpInst::Predicate Pred = Cond->getPredicate();
2021 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
2022 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
2023 return Cond->getOperand(0);
2024
2025 return nullptr;
2026}
2027
2028namespace {
2029
2030class StrlenVerifier {
2031public:
2032 explicit StrlenVerifier(const Loop *CurLoop, ScalarEvolution *SE,
2033 const TargetLibraryInfo *TLI)
2034 : CurLoop(CurLoop), SE(SE), TLI(TLI) {}
2035
2036 bool isValidStrlenIdiom() {
2037 // Give up if the loop has multiple blocks, multiple backedges, or
2038 // multiple exit blocks
2039 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1 ||
2040 !CurLoop->getUniqueExitBlock())
2041 return false;
2042
2043 // It should have a preheader and a branch instruction.
2044 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2045 if (!Preheader ||
2047 return false;
2048
2049 // The loop exit must be conditioned on an icmp with 0 the null terminator.
2050 // The icmp operand has to be a load on some SSA reg that increments
2051 // by 1 in the loop.
2052 BasicBlock *LoopBody = *CurLoop->block_begin();
2053
2054 // Skip if the body is too big as it most likely is not a strlen idiom.
2055 if (!LoopBody || LoopBody->size() >= 15)
2056 return false;
2057
2058 CondBrInst *LoopTerm = dyn_cast<CondBrInst>(LoopBody->getTerminator());
2059 if (!LoopTerm)
2060 return false;
2061 Value *LoopCond = matchCondition(LoopTerm, LoopBody);
2062 if (!LoopCond)
2063 return false;
2064
2065 LoadInst *LoopLoad = dyn_cast<LoadInst>(LoopCond);
2066 if (!LoopLoad || LoopLoad->getPointerAddressSpace() != 0)
2067 return false;
2068
2069 OperandType = LoopLoad->getType();
2070 if (!OperandType || !OperandType->isIntegerTy())
2071 return false;
2072
2073 // See if the pointer expression is an AddRec with constant step a of form
2074 // ({n,+,a}) where a is the width of the char type.
2075 Value *IncPtr = LoopLoad->getPointerOperand();
2076 const SCEV *LoadEv = SE->getSCEV(IncPtr);
2077 const APInt *Step;
2078 if (!match(LoadEv,
2079 m_scev_AffineAddRec(m_SCEV(LoadBaseEv), m_scev_APInt(Step))))
2080 return false;
2081
2082 LLVM_DEBUG(dbgs() << "pointer load scev: " << *LoadEv << "\n");
2083
2084 uint64_t StepSize = Step->getZExtValue();
2085
2086 // Verify that StepSize is consistent with platform char width.
2087 OpWidth = OperandType->getIntegerBitWidth();
2088 unsigned WcharSize = TLI->getWCharSize(*LoopLoad->getModule());
2089 if (OpWidth != 8 && OpWidth != 16 && OpWidth != 32)
2090 return false;
2091 if (StepSize != OpWidth / 8)
2092 return false;
2093 if (OpWidth >= 16) {
2094 if (OpWidth != WcharSize * 8)
2095 return false;
2096
2097 // Don't call `wcslen` if the base pointer isn't known to be aligned.
2098 const DataLayout &DL = LoopLoad->getDataLayout();
2099 Align OperandAlign = DL.getABITypeAlign(OperandType);
2100 if (LoopLoad->getAlign() < OperandAlign) {
2101 // For null pointers the load base number of trailing zeros may be
2102 // larger than what `Align` allows. So take log2 of operand alignment
2103 // instead and compare trailing zeros instead of alignments.
2104 if (SE->getMinTrailingZeros(LoadBaseEv) < Log2(OperandAlign))
2105 return false;
2106 }
2107 }
2108
2109 // Scan every instruction in the loop to ensure there are no side effects.
2110 for (Instruction &I : *LoopBody)
2111 if (I.mayHaveSideEffects())
2112 return false;
2113
2114 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
2115 if (!LoopExitBB)
2116 return false;
2117
2118 for (PHINode &PN : LoopExitBB->phis()) {
2119 if (!SE->isSCEVable(PN.getType()))
2120 return false;
2121
2122 const SCEV *Ev = SE->getSCEV(&PN);
2123 if (!Ev)
2124 return false;
2125
2126 LLVM_DEBUG(dbgs() << "loop exit phi scev: " << *Ev << "\n");
2127
2128 // Since we verified that the loop trip count will be a valid strlen
2129 // idiom, we can expand all lcssa phi with {n,+,1} as (n + strlen) and use
2130 // SCEVExpander materialize the loop output.
2131 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
2132 if (!AddRecEv || !AddRecEv->isAffine())
2133 return false;
2134
2135 // We only want RecAddExpr with recurrence step that is constant. This
2136 // is good enough for all the idioms we want to recognize. Later we expand
2137 // and materialize the recurrence as {base,+,a} -> (base + a * strlen)
2138 if (!isa<SCEVConstant>(AddRecEv->getStepRecurrence(*SE)))
2139 return false;
2140 }
2141
2142 return true;
2143 }
2144
2145public:
2146 const Loop *CurLoop;
2147 ScalarEvolution *SE;
2148 const TargetLibraryInfo *TLI;
2149
2150 unsigned OpWidth;
2151 ConstantInt *StepSizeCI;
2152 const SCEV *LoadBaseEv;
2154};
2155
2156} // namespace
2157
2158/// The Strlen Idiom we are trying to detect has the following structure
2159///
2160/// preheader:
2161/// ...
2162/// br label %body, ...
2163///
2164/// body:
2165/// ... ; %0 is incremented by a gep
2166/// %1 = load i8, ptr %0, align 1
2167/// %2 = icmp eq i8 %1, 0
2168/// br i1 %2, label %exit, label %body
2169///
2170/// exit:
2171/// %lcssa = phi [%0, %body], ...
2172///
2173/// We expect the strlen idiom to have a load of a character type that
2174/// is compared against '\0', and such load pointer operand must have scev
2175/// expression of the form {%str,+,c} where c is a ConstantInt of the
2176/// appropiate character width for the idiom, and %str is the base of the string
2177/// And, that all lcssa phis have the form {...,+,n} where n is a constant,
2178///
2179/// When transforming the output of the strlen idiom, the lccsa phi are
2180/// expanded using SCEVExpander as {base scev,+,a} -> (base scev + a * strlen)
2181/// and all subsequent uses are replaced. For example,
2182///
2183/// \code{.c}
2184/// const char* base = str;
2185/// while (*str != '\0')
2186/// ++str;
2187/// size_t result = str - base;
2188/// \endcode
2189///
2190/// will be transformed as follows: The idiom will be replaced by a strlen
2191/// computation to compute the address of the null terminator of the string.
2192///
2193/// \code{.c}
2194/// const char* base = str;
2195/// const char* end = base + strlen(str);
2196/// size_t result = end - base;
2197/// \endcode
2198///
2199/// In the case we index by an induction variable, as long as the induction
2200/// variable has a constant int increment, we can replace all such indvars
2201/// with the closed form computation of strlen
2202///
2203/// \code{.c}
2204/// size_t i = 0;
2205/// while (str[i] != '\0')
2206/// ++i;
2207/// size_t result = i;
2208/// \endcode
2209///
2210/// Will be replaced by
2211///
2212/// \code{.c}
2213/// size_t i = 0 + strlen(str);
2214/// size_t result = i;
2215/// \endcode
2216///
2217bool LoopIdiomRecognize::recognizeAndInsertStrLen() {
2218 if (DisableLIRP::All)
2219 return false;
2220
2221 StrlenVerifier Verifier(CurLoop, SE, TLI);
2222
2223 if (!Verifier.isValidStrlenIdiom())
2224 return false;
2225
2226 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2227 BasicBlock *LoopBody = *CurLoop->block_begin();
2228 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
2229 CondBrInst *LoopTerm = cast<CondBrInst>(LoopBody->getTerminator());
2230 assert(Preheader && LoopBody && LoopExitBB &&
2231 "Should be verified to be valid by StrlenVerifier");
2232
2233 if (Verifier.OpWidth == 8) {
2235 return false;
2236 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_strlen))
2237 return false;
2238 } else {
2240 return false;
2241 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_wcslen))
2242 return false;
2243 }
2244
2245 IRBuilder<> Builder(Preheader->getTerminator());
2246 Builder.SetCurrentDebugLocation(CurLoop->getStartLoc());
2247 SCEVExpander Expander(*SE, "strlen_idiom");
2248 Value *MaterialzedBase = Expander.expandCodeFor(
2249 Verifier.LoadBaseEv, Verifier.LoadBaseEv->getType(),
2250 Builder.GetInsertPoint());
2251
2252 Value *StrLenFunc = nullptr;
2253 if (Verifier.OpWidth == 8) {
2254 StrLenFunc = emitStrLen(MaterialzedBase, Builder, *DL, TLI);
2255 } else {
2256 StrLenFunc = emitWcsLen(MaterialzedBase, Builder, *DL, TLI);
2257 }
2258 assert(StrLenFunc && "Failed to emit strlen function.");
2259
2260 const SCEV *StrlenEv = SE->getSCEV(StrLenFunc);
2262 for (PHINode &PN : LoopExitBB->phis()) {
2263 // We can now materialize the loop output as all phi have scev {base,+,a}.
2264 // We expand the phi as:
2265 // %strlen = call i64 @strlen(%str)
2266 // %phi.new = base expression + step * %strlen
2267 const SCEV *Ev = SE->getSCEV(&PN);
2268 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
2269 const SCEVConstant *Step =
2271 const SCEV *Base = AddRecEv->getStart();
2272
2273 // It is safe to truncate to base since if base is narrower than size_t
2274 // the equivalent user code will have to truncate anyways.
2275 const SCEV *NewEv = SE->getAddExpr(
2277 StrlenEv, Base->getType())));
2278
2279 Value *MaterializedPHI = Expander.expandCodeFor(NewEv, NewEv->getType(),
2280 Builder.GetInsertPoint());
2281 Expander.clear();
2282 PN.replaceAllUsesWith(MaterializedPHI);
2283 Cleanup.push_back(&PN);
2284 }
2285
2286 // All LCSSA Loop Phi are dead, the left over dead loop body can be cleaned
2287 // up by later passes
2288 for (PHINode *PN : Cleanup)
2290
2291 // LoopDeletion only delete invariant loops with known trip-count. We can
2292 // update the condition so it will reliablely delete the invariant loop
2293 assert((LoopTerm->getSuccessor(0) == LoopBody ||
2294 LoopTerm->getSuccessor(1) == LoopBody) &&
2295 "loop body must have a successor that is it self");
2296 ConstantInt *NewLoopCond = LoopTerm->getSuccessor(0) == LoopBody
2297 ? Builder.getFalse()
2298 : Builder.getTrue();
2299 LoopTerm->setCondition(NewLoopCond);
2300 SE->forgetLoop(CurLoop);
2301
2302 ++NumStrLen;
2303 LLVM_DEBUG(dbgs() << " Formed strlen idiom: " << *StrLenFunc << "\n");
2304 ORE.emit([&]() {
2305 return OptimizationRemark(DEBUG_TYPE, "recognizeAndInsertStrLen",
2306 CurLoop->getStartLoc(), Preheader)
2307 << "Transformed " << StrLenFunc->getName() << " loop idiom";
2308 });
2309
2310 return true;
2311}
2312
2313/// Check if the given conditional branch is based on an unsigned less-than
2314/// comparison between a variable and a constant, and if the comparison is false
2315/// the control yields to the loop entry. If the branch matches the behaviour,
2316/// the variable involved in the comparison is returned.
2318 APInt &Threshold) {
2320 if (!Cond)
2321 return nullptr;
2322
2323 ConstantInt *CmpConst = dyn_cast<ConstantInt>(Cond->getOperand(1));
2324 if (!CmpConst)
2325 return nullptr;
2326
2327 BasicBlock *FalseSucc = BI->getSuccessor(1);
2328 ICmpInst::Predicate Pred = Cond->getPredicate();
2329
2330 if (Pred == ICmpInst::ICMP_ULT && FalseSucc == LoopEntry) {
2331 Threshold = CmpConst->getValue();
2332 return Cond->getOperand(0);
2333 }
2334
2335 return nullptr;
2336}
2337
2338// Check if the recurrence variable `VarX` is in the right form to create
2339// the idiom. Returns the value coerced to a PHINode if so.
2341 BasicBlock *LoopEntry) {
2342 auto *PhiX = dyn_cast<PHINode>(VarX);
2343 if (PhiX && PhiX->getParent() == LoopEntry &&
2344 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
2345 return PhiX;
2346 return nullptr;
2347}
2348
2349/// Return true if the idiom is detected in the loop.
2350///
2351/// Additionally:
2352/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2353/// or nullptr if there is no such.
2354/// 2) \p CntPhi is set to the corresponding phi node
2355/// or nullptr if there is no such.
2356/// 3) \p InitX is set to the value whose CTLZ could be used.
2357/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2358/// 5) \p Threshold is set to the constant involved in the unsigned less-than
2359/// comparison.
2360///
2361/// The core idiom we are trying to detect is:
2362/// \code
2363/// if (x0 < 2)
2364/// goto loop-exit // the precondition of the loop
2365/// cnt0 = init-val
2366/// do {
2367/// x = phi (x0, x.next); //PhiX
2368/// cnt = phi (cnt0, cnt.next)
2369///
2370/// cnt.next = cnt + 1;
2371/// ...
2372/// x.next = x >> 1; // DefX
2373/// } while (x >= 4)
2374/// loop-exit:
2375/// \endcode
2377 Intrinsic::ID &IntrinID,
2378 Value *&InitX, Instruction *&CntInst,
2379 PHINode *&CntPhi, Instruction *&DefX,
2380 APInt &Threshold) {
2381 BasicBlock *LoopEntry;
2382
2383 DefX = nullptr;
2384 CntInst = nullptr;
2385 CntPhi = nullptr;
2386 LoopEntry = *(CurLoop->block_begin());
2387
2388 // step 1: Check if the loop-back branch is in desirable form.
2389 auto *EntryBI = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2390 if (!EntryBI)
2391 return false;
2392 if (Value *T = matchShiftULTCondition(EntryBI, LoopEntry, Threshold))
2393 DefX = dyn_cast<Instruction>(T);
2394 else
2395 return false;
2396
2397 // step 2: Check the recurrence of variable X
2398 if (!DefX || !isa<PHINode>(DefX))
2399 return false;
2400
2401 PHINode *VarPhi = cast<PHINode>(DefX);
2402 int Idx = VarPhi->getBasicBlockIndex(LoopEntry);
2403 if (Idx == -1)
2404 return false;
2405
2406 DefX = dyn_cast<Instruction>(VarPhi->getIncomingValue(Idx));
2407 if (!DefX || DefX->getNumOperands() == 0 || DefX->getOperand(0) != VarPhi)
2408 return false;
2409
2410 // step 3: detect instructions corresponding to "x.next = x >> 1"
2411 if (DefX->getOpcode() != Instruction::LShr)
2412 return false;
2413
2414 IntrinID = Intrinsic::ctlz;
2416 if (!Shft || !Shft->isOne())
2417 return false;
2418
2419 InitX = VarPhi->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2420
2421 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2422 // or cnt.next = cnt + -1.
2423 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2424 // then all uses of "cnt.next" could be optimized to the trip count
2425 // plus "cnt0". Currently it is not optimized.
2426 // This step could be used to detect POPCNT instruction:
2427 // cnt.next = cnt + (x.next & 1)
2428 for (Instruction &Inst :
2429 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2430 if (Inst.getOpcode() != Instruction::Add)
2431 continue;
2432
2434 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2435 continue;
2436
2437 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2438 if (!Phi)
2439 continue;
2440
2441 CntInst = &Inst;
2442 CntPhi = Phi;
2443 break;
2444 }
2445 if (!CntInst)
2446 return false;
2447
2448 return true;
2449}
2450
2451/// Return true iff the idiom is detected in the loop.
2452///
2453/// Additionally:
2454/// 1) \p CntInst is set to the instruction counting the population bit.
2455/// 2) \p CntPhi is set to the corresponding phi node.
2456/// 3) \p Var is set to the value whose population bits are being counted.
2457///
2458/// The core idiom we are trying to detect is:
2459/// \code
2460/// if (x0 != 0)
2461/// goto loop-exit // the precondition of the loop
2462/// cnt0 = init-val;
2463/// do {
2464/// x1 = phi (x0, x2);
2465/// cnt1 = phi(cnt0, cnt2);
2466///
2467/// cnt2 = cnt1 + 1;
2468/// ...
2469/// x2 = x1 & (x1 - 1);
2470/// ...
2471/// } while(x != 0);
2472///
2473/// loop-exit:
2474/// \endcode
2475static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
2476 Instruction *&CntInst, PHINode *&CntPhi,
2477 Value *&Var) {
2478 // step 1: Check to see if the look-back branch match this pattern:
2479 // "if (a!=0) goto loop-entry".
2480 BasicBlock *LoopEntry;
2481 Instruction *DefX2, *CountInst;
2482 Value *VarX1, *VarX0;
2483 PHINode *PhiX, *CountPhi;
2484
2485 DefX2 = CountInst = nullptr;
2486 VarX1 = VarX0 = nullptr;
2487 PhiX = CountPhi = nullptr;
2488 LoopEntry = *(CurLoop->block_begin());
2489
2490 // step 1: Check if the loop-back branch is in desirable form.
2491 {
2492 auto *LoopTerm = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2493 if (!LoopTerm)
2494 return false;
2495 DefX2 = dyn_cast_or_null<Instruction>(matchCondition(LoopTerm, LoopEntry));
2496 }
2497
2498 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
2499 {
2500 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
2501 return false;
2502
2503 BinaryOperator *SubOneOp;
2504
2505 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
2506 VarX1 = DefX2->getOperand(1);
2507 else {
2508 VarX1 = DefX2->getOperand(0);
2509 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
2510 }
2511 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
2512 return false;
2513
2514 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
2515 if (!Dec ||
2516 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
2517 (SubOneOp->getOpcode() == Instruction::Add &&
2518 Dec->isMinusOne()))) {
2519 return false;
2520 }
2521 }
2522
2523 // step 3: Check the recurrence of variable X
2524 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
2525 if (!PhiX)
2526 return false;
2527
2528 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
2529 {
2530 CountInst = nullptr;
2531 for (Instruction &Inst :
2532 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2533 if (Inst.getOpcode() != Instruction::Add)
2534 continue;
2535
2537 if (!Inc || !Inc->isOne())
2538 continue;
2539
2540 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2541 if (!Phi)
2542 continue;
2543
2544 // Check if the result of the instruction is live of the loop.
2545 bool LiveOutLoop = false;
2546 for (User *U : Inst.users()) {
2547 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
2548 LiveOutLoop = true;
2549 break;
2550 }
2551 }
2552
2553 if (LiveOutLoop) {
2554 CountInst = &Inst;
2555 CountPhi = Phi;
2556 break;
2557 }
2558 }
2559
2560 if (!CountInst)
2561 return false;
2562 }
2563
2564 // step 5: check if the precondition is in this form:
2565 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
2566 {
2567 auto *PreCondBr = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2568 if (!PreCondBr)
2569 return false;
2570 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
2571 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
2572 return false;
2573
2574 CntInst = CountInst;
2575 CntPhi = CountPhi;
2576 Var = T;
2577 }
2578
2579 return true;
2580}
2581
2582/// Return true if the idiom is detected in the loop.
2583///
2584/// Additionally:
2585/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2586/// or nullptr if there is no such.
2587/// 2) \p CntPhi is set to the corresponding phi node
2588/// or nullptr if there is no such.
2589/// 3) \p Var is set to the value whose CTLZ could be used.
2590/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2591///
2592/// The core idiom we are trying to detect is:
2593/// \code
2594/// if (x0 == 0)
2595/// goto loop-exit // the precondition of the loop
2596/// cnt0 = init-val;
2597/// do {
2598/// x = phi (x0, x.next); //PhiX
2599/// cnt = phi(cnt0, cnt.next);
2600///
2601/// cnt.next = cnt + 1;
2602/// ...
2603/// x.next = x >> 1; // DefX
2604/// ...
2605/// } while(x.next != 0);
2606///
2607/// loop-exit:
2608/// \endcode
2609static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
2610 Intrinsic::ID &IntrinID, Value *&InitX,
2611 Instruction *&CntInst, PHINode *&CntPhi,
2612 Instruction *&DefX) {
2613 BasicBlock *LoopEntry;
2614 Value *VarX = nullptr;
2615
2616 DefX = nullptr;
2617 CntInst = nullptr;
2618 CntPhi = nullptr;
2619 LoopEntry = *(CurLoop->block_begin());
2620
2621 // step 1: Check if the loop-back branch is in desirable form.
2622 auto *LoopTerm = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2623 if (!LoopTerm)
2624 return false;
2625 DefX = dyn_cast_or_null<Instruction>(matchCondition(LoopTerm, LoopEntry));
2626
2627 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
2628 if (!DefX || !DefX->isShift())
2629 return false;
2630 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
2631 Intrinsic::ctlz;
2633 if (!Shft || !Shft->isOne())
2634 return false;
2635 VarX = DefX->getOperand(0);
2636
2637 // step 3: Check the recurrence of variable X
2638 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
2639 if (!PhiX)
2640 return false;
2641
2642 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2643
2644 // Make sure the initial value can't be negative otherwise the ashr in the
2645 // loop might never reach zero which would make the loop infinite.
2646 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
2647 return false;
2648
2649 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2650 // or cnt.next = cnt + -1.
2651 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2652 // then all uses of "cnt.next" could be optimized to the trip count
2653 // plus "cnt0". Currently it is not optimized.
2654 // This step could be used to detect POPCNT instruction:
2655 // cnt.next = cnt + (x.next & 1)
2656 for (Instruction &Inst :
2657 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2658 if (Inst.getOpcode() != Instruction::Add)
2659 continue;
2660
2662 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2663 continue;
2664
2665 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2666 if (!Phi)
2667 continue;
2668
2669 CntInst = &Inst;
2670 CntPhi = Phi;
2671 break;
2672 }
2673 if (!CntInst)
2674 return false;
2675
2676 return true;
2677}
2678
2679// Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
2680// profitable if we delete the loop.
2681bool LoopIdiomRecognize::isProfitableToInsertFFS(Intrinsic::ID IntrinID,
2682 Value *InitX, bool ZeroCheck,
2683 size_t CanonicalSize) {
2684 const Value *Args[] = {InitX,
2685 ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
2686
2687 uint32_t HeaderSize = CurLoop->getHeader()->size();
2688
2689 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
2690 InstructionCost Cost = TTI->getIntrinsicInstrCost(
2692 if (HeaderSize != CanonicalSize && Cost > TargetTransformInfo::TCC_Basic)
2693 return false;
2694
2695 return true;
2696}
2697
2698/// Convert CTLZ / CTTZ idiom loop into countable loop.
2699/// If CTLZ / CTTZ inserted as a new trip count returns true; otherwise,
2700/// returns false.
2701bool LoopIdiomRecognize::insertFFSIfProfitable(Intrinsic::ID IntrinID,
2702 Value *InitX, Instruction *DefX,
2703 PHINode *CntPhi,
2704 Instruction *CntInst) {
2705 bool IsCntPhiUsedOutsideLoop = false;
2706 for (User *U : CntPhi->users())
2707 if (!CurLoop->contains(cast<Instruction>(U))) {
2708 IsCntPhiUsedOutsideLoop = true;
2709 break;
2710 }
2711 bool IsCntInstUsedOutsideLoop = false;
2712 for (User *U : CntInst->users())
2713 if (!CurLoop->contains(cast<Instruction>(U))) {
2714 IsCntInstUsedOutsideLoop = true;
2715 break;
2716 }
2717 // If both CntInst and CntPhi are used outside the loop the profitability
2718 // is questionable.
2719 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
2720 return false;
2721
2722 // For some CPUs result of CTLZ(X) intrinsic is undefined
2723 // when X is 0. If we can not guarantee X != 0, we need to check this
2724 // when expand.
2725 bool ZeroCheck = false;
2726 // It is safe to assume Preheader exist as it was checked in
2727 // parent function RunOnLoop.
2728 BasicBlock *PH = CurLoop->getLoopPreheader();
2729
2730 // If we are using the count instruction outside the loop, make sure we
2731 // have a zero check as a precondition. Without the check the loop would run
2732 // one iteration for before any check of the input value. This means 0 and 1
2733 // would have identical behavior in the original loop and thus
2734 if (!IsCntPhiUsedOutsideLoop) {
2735 auto *PreCondBB = PH->getSinglePredecessor();
2736 auto *PreCondBI =
2737 PreCondBB ? dyn_cast<CondBrInst>(PreCondBB->getTerminator()) : nullptr;
2738 if (!(PreCondBI && matchCondition(PreCondBI, PH) == InitX) &&
2740 InitX, SimplifyQuery(*DL, DT, /*AC=*/nullptr, PH->getTerminator())))
2741 return false;
2742 ZeroCheck = true;
2743 }
2744
2745 // FFS idiom loop has only 6 instructions:
2746 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2747 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2748 // %shr = ashr %n.addr.0, 1
2749 // %tobool = icmp eq %shr, 0
2750 // %inc = add nsw %i.0, 1
2751 // br i1 %tobool
2752 size_t IdiomCanonicalSize = 6;
2753 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2754 return false;
2755
2756 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2757 DefX->getDebugLoc(), ZeroCheck,
2758 IsCntPhiUsedOutsideLoop);
2759 return true;
2760}
2761
2762/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
2763/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
2764/// trip count returns true; otherwise, returns false.
2765bool LoopIdiomRecognize::recognizeAndInsertFFS() {
2766 // Give up if the loop has multiple blocks or multiple backedges.
2767 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2768 return false;
2769
2770 Intrinsic::ID IntrinID;
2771 Value *InitX;
2772 Instruction *DefX = nullptr;
2773 PHINode *CntPhi = nullptr;
2774 Instruction *CntInst = nullptr;
2775
2776 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, CntInst, CntPhi,
2777 DefX))
2778 return false;
2779
2780 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2781}
2782
2783bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {
2784 // Give up if the loop has multiple blocks or multiple backedges.
2785 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2786 return false;
2787
2788 Intrinsic::ID IntrinID;
2789 Value *InitX;
2790 Instruction *DefX = nullptr;
2791 PHINode *CntPhi = nullptr;
2792 Instruction *CntInst = nullptr;
2793
2794 APInt LoopThreshold;
2795 if (!detectShiftUntilLessThanIdiom(CurLoop, *DL, IntrinID, InitX, CntInst,
2796 CntPhi, DefX, LoopThreshold))
2797 return false;
2798
2799 if (LoopThreshold == 2) {
2800 // Treat as regular FFS.
2801 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2802 }
2803
2804 // Look for Floor Log2 Idiom.
2805 if (LoopThreshold != 4)
2806 return false;
2807
2808 // Abort if CntPhi is used outside of the loop.
2809 for (User *U : CntPhi->users())
2810 if (!CurLoop->contains(cast<Instruction>(U)))
2811 return false;
2812
2813 // It is safe to assume Preheader exist as it was checked in
2814 // parent function RunOnLoop.
2815 BasicBlock *PH = CurLoop->getLoopPreheader();
2816 auto *PreCondBB = PH->getSinglePredecessor();
2817 if (!PreCondBB)
2818 return false;
2819 auto *PreCondBI = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2820 if (!PreCondBI)
2821 return false;
2822
2823 APInt PreLoopThreshold;
2824 if (matchShiftULTCondition(PreCondBI, PH, PreLoopThreshold) != InitX ||
2825 PreLoopThreshold != 2)
2826 return false;
2827
2828 bool ZeroCheck = true;
2829
2830 // the loop has only 6 instructions:
2831 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2832 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2833 // %shr = ashr %n.addr.0, 1
2834 // %tobool = icmp ult %n.addr.0, C
2835 // %inc = add nsw %i.0, 1
2836 // br i1 %tobool
2837 size_t IdiomCanonicalSize = 6;
2838 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2839 return false;
2840
2841 // log2(x) = w − 1 − clz(x)
2842 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2843 DefX->getDebugLoc(), ZeroCheck,
2844 /*IsCntPhiUsedOutsideLoop=*/false,
2845 /*InsertSub=*/true);
2846 return true;
2847}
2848
2849/// Recognizes a population count idiom in a non-countable loop.
2850///
2851/// If detected, transforms the relevant code to issue the popcount intrinsic
2852/// function call, and returns true; otherwise, returns false.
2853bool LoopIdiomRecognize::recognizePopcount() {
2854 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
2855 return false;
2856
2857 // Counting population are usually conducted by few arithmetic instructions.
2858 // Such instructions can be easily "absorbed" by vacant slots in a
2859 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
2860 // in a compact loop.
2861
2862 // Give up if the loop has multiple blocks or multiple backedges.
2863 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2864 return false;
2865
2866 BasicBlock *LoopBody = *(CurLoop->block_begin());
2867 if (LoopBody->size() >= 20) {
2868 // The loop is too big, bail out.
2869 return false;
2870 }
2871
2872 // It should have a preheader containing nothing but an unconditional branch.
2873 BasicBlock *PH = CurLoop->getLoopPreheader();
2874 if (!PH || &PH->front() != PH->getTerminator())
2875 return false;
2876 auto *EntryBI = dyn_cast<UncondBrInst>(PH->getTerminator());
2877 if (!EntryBI)
2878 return false;
2879
2880 // It should have a precondition block where the generated popcount intrinsic
2881 // function can be inserted.
2882 auto *PreCondBB = PH->getSinglePredecessor();
2883 if (!PreCondBB)
2884 return false;
2885 auto *PreCondBI = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2886 if (!PreCondBI)
2887 return false;
2888
2889 Instruction *CntInst;
2890 PHINode *CntPhi;
2891 Value *Val;
2892 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
2893 return false;
2894
2895 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
2896 return true;
2897}
2898
2900 const DebugLoc &DL) {
2901 Value *Ops[] = {Val};
2902 Type *Tys[] = {Val->getType()};
2903
2905 return IRBuilder.CreateIntrinsic(Intrinsic::ctpop, Tys, Ops);
2906}
2907
2909 const DebugLoc &DL, bool ZeroCheck,
2910 Intrinsic::ID IID) {
2911 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
2912 Type *Tys[] = {Val->getType()};
2913
2915 return IRBuilder.CreateIntrinsic(IID, Tys, Ops);
2916}
2917
2918/// Transform the following loop (Using CTLZ, CTTZ is similar):
2919/// loop:
2920/// CntPhi = PHI [Cnt0, CntInst]
2921/// PhiX = PHI [InitX, DefX]
2922/// CntInst = CntPhi + 1
2923/// DefX = PhiX >> 1
2924/// LOOP_BODY
2925/// Br: loop if (DefX != 0)
2926/// Use(CntPhi) or Use(CntInst)
2927///
2928/// Into:
2929/// If CntPhi used outside the loop:
2930/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
2931/// Count = CountPrev + 1
2932/// else
2933/// Count = BitWidth(InitX) - CTLZ(InitX)
2934/// loop:
2935/// CntPhi = PHI [Cnt0, CntInst]
2936/// PhiX = PHI [InitX, DefX]
2937/// PhiCount = PHI [Count, Dec]
2938/// CntInst = CntPhi + 1
2939/// DefX = PhiX >> 1
2940/// Dec = PhiCount - 1
2941/// LOOP_BODY
2942/// Br: loop if (Dec != 0)
2943/// Use(CountPrev + Cnt0) // Use(CntPhi)
2944/// or
2945/// Use(Count + Cnt0) // Use(CntInst)
2946///
2947/// If LOOP_BODY is empty the loop will be deleted.
2948/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
2949void LoopIdiomRecognize::transformLoopToCountable(
2950 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
2951 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
2952 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop, bool InsertSub) {
2953 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
2954 IRBuilder<> Builder(Preheader->getTerminator());
2955 Builder.SetCurrentDebugLocation(DL);
2956
2957 // If there are no uses of CntPhi crate:
2958 // Count = BitWidth - CTLZ(InitX);
2959 // NewCount = Count;
2960 // If there are uses of CntPhi create:
2961 // NewCount = BitWidth - CTLZ(InitX >> 1);
2962 // Count = NewCount + 1;
2963 Value *InitXNext;
2964 if (IsCntPhiUsedOutsideLoop) {
2965 if (DefX->getOpcode() == Instruction::AShr)
2966 InitXNext = Builder.CreateAShr(InitX, 1);
2967 else if (DefX->getOpcode() == Instruction::LShr)
2968 InitXNext = Builder.CreateLShr(InitX, 1);
2969 else if (DefX->getOpcode() == Instruction::Shl) // cttz
2970 InitXNext = Builder.CreateShl(InitX, 1);
2971 else
2972 llvm_unreachable("Unexpected opcode!");
2973 } else
2974 InitXNext = InitX;
2975 Value *Count =
2976 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
2977 Type *CountTy = Count->getType();
2978 Count = Builder.CreateSub(
2979 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
2980 if (InsertSub)
2981 Count = Builder.CreateSub(Count, ConstantInt::get(CountTy, 1));
2982 Value *NewCount = Count;
2983 if (IsCntPhiUsedOutsideLoop)
2984 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
2985
2986 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
2987
2988 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
2989 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
2990 // If the counter was being incremented in the loop, add NewCount to the
2991 // counter's initial value, but only if the initial value is not zero.
2992 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2993 if (!InitConst || !InitConst->isZero())
2994 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2995 } else {
2996 // If the count was being decremented in the loop, subtract NewCount from
2997 // the counter's initial value.
2998 NewCount = Builder.CreateSub(CntInitVal, NewCount);
2999 }
3000
3001 // Step 2: Insert new IV and loop condition:
3002 // loop:
3003 // ...
3004 // PhiCount = PHI [Count, Dec]
3005 // ...
3006 // Dec = PhiCount - 1
3007 // ...
3008 // Br: loop if (Dec != 0)
3009 BasicBlock *Body = *(CurLoop->block_begin());
3010 auto *LbBr = cast<CondBrInst>(Body->getTerminator());
3011 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
3012
3013 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi");
3014 TcPhi->insertBefore(Body->begin());
3015
3016 Builder.SetInsertPoint(LbCond);
3017 Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
3018 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
3019
3020 TcPhi->addIncoming(Count, Preheader);
3021 TcPhi->addIncoming(TcDec, Body);
3022
3023 CmpInst::Predicate Pred =
3024 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
3025 LbCond->setPredicate(Pred);
3026 LbCond->setOperand(0, TcDec);
3027 LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
3028
3029 // Step 3: All the references to the original counter outside
3030 // the loop are replaced with the NewCount
3031 if (IsCntPhiUsedOutsideLoop)
3032 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
3033 else
3034 CntInst->replaceUsesOutsideBlock(NewCount, Body);
3035
3036 // step 4: Forget the "non-computable" trip-count SCEV associated with the
3037 // loop. The loop would otherwise not be deleted even if it becomes empty.
3038 SE->forgetLoop(CurLoop);
3039}
3040
3041void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
3042 Instruction *CntInst,
3043 PHINode *CntPhi, Value *Var) {
3044 BasicBlock *PreHead = CurLoop->getLoopPreheader();
3045 auto *PreCondBr = cast<CondBrInst>(PreCondBB->getTerminator());
3046 const DebugLoc &DL = CntInst->getDebugLoc();
3047
3048 // Assuming before transformation, the loop is following:
3049 // if (x) // the precondition
3050 // do { cnt++; x &= x - 1; } while(x);
3051
3052 // Step 1: Insert the ctpop instruction at the end of the precondition block
3053 IRBuilder<> Builder(PreCondBr);
3054 Value *PopCnt, *NewCount, *TripCnt;
3055 {
3056 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
3057 NewCount =
3058 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
3059
3060 if (NewCount != PopCnt)
3061 (cast<Instruction>(NewCount))->setDebugLoc(DL);
3062
3063 // TripCnt is exactly the number of iterations the loop has
3064 TripCnt = PopCnt;
3065
3066 // If the population counter's initial value is not zero, insert Add Inst.
3067 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
3068 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
3069 if (!InitConst || !InitConst->isZero()) {
3070 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
3071 (cast<Instruction>(NewCount))->setDebugLoc(DL);
3072 }
3073 }
3074
3075 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
3076 // "if (TripCnt == 0) loop-exit". Without this change, the intrinsic
3077 // function would be partial dead code, and downstream passes will drag
3078 // it back from the precondition block to the preheader.
3079 {
3080 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
3081
3082 Value *Opnd0 = TripCnt;
3083 Value *Opnd1 = ConstantInt::get(TripCnt->getType(), 0);
3084 if (PreCond->getOperand(0) != Var)
3085 std::swap(Opnd0, Opnd1);
3086
3087 ICmpInst *NewPreCond = cast<ICmpInst>(
3088 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
3089 PreCondBr->setCondition(NewPreCond);
3090
3092 }
3093
3094 // Step 3: Note that the population count is exactly the trip count of the
3095 // loop in question, which enable us to convert the loop from noncountable
3096 // loop into a countable one. The benefit is twofold:
3097 //
3098 // - If the loop only counts population, the entire loop becomes dead after
3099 // the transformation. It is a lot easier to prove a countable loop dead
3100 // than to prove a noncountable one. (In some C dialects, an infinite loop
3101 // isn't dead even if it computes nothing useful. In general, DCE needs
3102 // to prove a noncountable loop finite before safely delete it.)
3103 //
3104 // - If the loop also performs something else, it remains alive.
3105 // Since it is transformed to countable form, it can be aggressively
3106 // optimized by some optimizations which are in general not applicable
3107 // to a noncountable loop.
3108 //
3109 // After this step, this loop (conceptually) would look like following:
3110 // newcnt = __builtin_ctpop(x);
3111 // t = newcnt;
3112 // if (x)
3113 // do { cnt++; x &= x-1; t--) } while (t > 0);
3114 BasicBlock *Body = *(CurLoop->block_begin());
3115 {
3116 auto *LbBr = cast<CondBrInst>(Body->getTerminator());
3117 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
3118 Type *Ty = TripCnt->getType();
3119
3120 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi");
3121 TcPhi->insertBefore(Body->begin());
3122
3123 Builder.SetInsertPoint(LbCond);
3125 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), "tcdec",
3126 /*HasNUW=*/true, /*HasNSW=*/false));
3127
3128 TcPhi->addIncoming(TripCnt, PreHead);
3129 TcPhi->addIncoming(TcDec, Body);
3130
3131 CmpInst::Predicate Pred =
3132 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_EQ;
3133 LbCond->setPredicate(Pred);
3134 LbCond->setOperand(0, TcDec);
3135 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
3136 }
3137
3138 // Step 4: All the references to the original population counter outside
3139 // the loop are replaced with the NewCount -- the value returned from
3140 // __builtin_ctpop().
3141 CntInst->replaceUsesOutsideBlock(NewCount, Body);
3142
3143 // step 5: Forget the "non-computable" trip-count SCEV associated with the
3144 // loop. The loop would otherwise not be deleted even if it becomes empty.
3145 SE->forgetLoop(CurLoop);
3146}
3147
3148/// Match loop-invariant value.
3149template <typename SubPattern_t> struct match_LoopInvariant {
3150 SubPattern_t SubPattern;
3151 const Loop *L;
3152
3153 match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
3154 : SubPattern(SP), L(L) {}
3155
3156 template <typename ITy> bool match(ITy *V) const {
3157 return L->isLoopInvariant(V) && SubPattern.match(V);
3158 }
3159};
3160
3161/// Matches if the value is loop-invariant.
3162template <typename Ty>
3163inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
3164 return match_LoopInvariant<Ty>(M, L);
3165}
3166
3167/// Return true if the idiom is detected in the loop.
3168///
3169/// The core idiom we are trying to detect is:
3170/// \code
3171/// entry:
3172/// <...>
3173/// %bitmask = shl i32 1, %bitpos
3174/// br label %loop
3175///
3176/// loop:
3177/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
3178/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
3179/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
3180/// %x.next = shl i32 %x.curr, 1
3181/// <...>
3182/// br i1 %x.curr.isbitunset, label %loop, label %end
3183///
3184/// end:
3185/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3186/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3187/// <...>
3188/// \endcode
3189static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
3190 Value *&BitMask, Value *&BitPos,
3191 Value *&CurrX, Instruction *&NextX) {
3193 " Performing shift-until-bittest idiom detection.\n");
3194
3195 // Give up if the loop has multiple blocks or multiple backedges.
3196 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
3197 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
3198 return false;
3199 }
3200
3201 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3202 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3203 assert(LoopPreheaderBB && "There is always a loop preheader.");
3204
3205 using namespace PatternMatch;
3206
3207 // Step 1: Check if the loop backedge is in desirable form.
3208
3209 CmpPredicate Pred;
3210 Value *CmpLHS, *CmpRHS;
3211 BasicBlock *TrueBB, *FalseBB;
3212 if (!match(LoopHeaderBB->getTerminator(),
3213 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
3214 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
3215 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
3216 return false;
3217 }
3218
3219 // Step 2: Check if the backedge's condition is in desirable form.
3220
3221 auto MatchVariableBitMask = [&]() {
3222 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
3223 match(CmpLHS,
3224 m_c_And(m_Value(CurrX),
3226 m_Value(BitMask),
3227 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
3228 CurLoop))));
3229 };
3230
3231 auto MatchDecomposableConstantBitMask = [&]() {
3232 auto Res = llvm::decomposeBitTestICmp(
3233 CmpLHS, CmpRHS, Pred, /*LookThroughTrunc=*/true,
3234 /*AllowNonZeroC=*/false, /*DecomposeAnd=*/true);
3235 if (Res && Res->Mask.isPowerOf2()) {
3236 assert(ICmpInst::isEquality(Res->Pred));
3237 Pred = Res->Pred;
3238 CurrX = Res->X;
3239 BitMask = ConstantInt::get(CurrX->getType(), Res->Mask);
3240 BitPos = ConstantInt::get(CurrX->getType(), Res->Mask.logBase2());
3241 return true;
3242 }
3243 return false;
3244 };
3245
3246 if (!MatchVariableBitMask() && !MatchDecomposableConstantBitMask()) {
3247 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
3248 return false;
3249 }
3250
3251 // Step 3: Check if the recurrence is in desirable form.
3252 auto *CurrXPN = dyn_cast<PHINode>(CurrX);
3253 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
3254 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
3255 return false;
3256 }
3257
3258 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
3259 NextX =
3260 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
3261
3262 assert(CurLoop->isLoopInvariant(BaseX) &&
3263 "Expected BaseX to be available in the preheader!");
3264
3265 if (!NextX || (!match(NextX, m_Shl(m_Specific(CurrX), m_One())) &&
3266 !match(NextX, m_LShr(m_Specific(CurrX), m_One())))) {
3267 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
3268 return false;
3269 }
3270
3271 // Step 4: Check if the backedge's destinations are in desirable form.
3272
3274 "Should only get equality predicates here.");
3275
3276 // cmp-br is commutative, so canonicalize to a single variant.
3277 if (Pred != ICmpInst::Predicate::ICMP_EQ) {
3278 Pred = ICmpInst::getInversePredicate(Pred);
3279 std::swap(TrueBB, FalseBB);
3280 }
3281
3282 // We expect to exit loop when comparison yields false,
3283 // so when it yields true we should branch back to loop header.
3284 if (TrueBB != LoopHeaderBB) {
3285 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
3286 return false;
3287 }
3288
3289 // Okay, idiom checks out.
3290 return true;
3291}
3292
3294 BasicBlock *Preheader,
3295 const DataLayout &DL,
3296 DominatorTree *DT) {
3297 using namespace PatternMatch;
3298
3299 auto *Pos = dyn_cast<ConstantInt>(BitPos);
3300 unsigned Bitwidth = X->getType()->getScalarSizeInBits();
3301 if (!Pos || Bitwidth == 1 || Pos->getValue().uge(Bitwidth))
3302 return false;
3303
3304 SimplifyQuery SQ(DL, DT, /*AC=*/nullptr, Preheader->getTerminator());
3305 if (!isKnownNonZero(X, SQ))
3306 return false;
3307 if (Pos->isZero())
3308 return true;
3309
3310 // The guard must rule out set bits below BitPos; those bits can never
3311 // reach the tested position when X shifts right.
3312 BasicBlock *GuardBB = Preheader->getSinglePredecessor();
3313 if (!GuardBB)
3314 return false;
3315 auto *Guard = dyn_cast<CondBrInst>(GuardBB->getTerminator());
3316 if (!Guard)
3317 return false;
3318
3319 CmpPredicate Pred;
3320 Value *LHS;
3321 if (!match(Guard->getCondition(), m_ICmp(Pred, m_Value(LHS), m_Zero())) ||
3322 !ICmpInst::isEquality(Pred))
3323 return false;
3324
3325 const APInt *Mask;
3326 if (!match(LHS, m_And(m_Specific(X), m_APInt(Mask))))
3327 return false;
3328
3329 BasicBlock *ZeroSuccessor =
3330 Guard->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 0 : 1);
3331 if (ZeroSuccessor != Preheader)
3332 return false;
3333
3334 return Mask->countr_one() >= Pos->getZExtValue();
3335}
3336
3337/// Look for the following loop:
3338/// \code
3339/// entry:
3340/// <...>
3341/// %bitmask = shl i32 1, %bitpos
3342/// br label %loop
3343///
3344/// loop:
3345/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
3346/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
3347/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
3348/// %x.next = shl i32 %x.curr, 1
3349/// <...>
3350/// br i1 %x.curr.isbitunset, label %loop, label %end
3351///
3352/// end:
3353/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3354/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3355/// <...>
3356/// \endcode
3357///
3358/// And transform it into:
3359/// \code
3360/// entry:
3361/// %bitmask = shl i32 1, %bitpos
3362/// %lowbitmask = add i32 %bitmask, -1
3363/// %mask = or i32 %lowbitmask, %bitmask
3364/// %x.masked = and i32 %x, %mask
3365/// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
3366/// i1 true)
3367/// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
3368/// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
3369/// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
3370/// %tripcount = add i32 %backedgetakencount, 1
3371/// %x.curr = shl i32 %x, %backedgetakencount
3372/// %x.next = shl i32 %x, %tripcount
3373/// br label %loop
3374///
3375/// loop:
3376/// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
3377/// %loop.iv.next = add nuw i32 %loop.iv, 1
3378/// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
3379/// <...>
3380/// br i1 %loop.ivcheck, label %end, label %loop
3381///
3382/// end:
3383/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3384/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3385/// <...>
3386/// \endcode
3387/// A logical right-shift recurrence uses cttz of X shifted by BitPos instead,
3388/// provided the preheader proves that the loop will reach a set bit.
3389bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
3390 bool MadeChange = false;
3391
3392 Value *X, *BitMask, *BitPos, *XCurr;
3393 Instruction *XNext;
3394 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
3395 XNext)) {
3397 " shift-until-bittest idiom detection failed.\n");
3398 return MadeChange;
3399 }
3400 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
3401
3402 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3403 // but is it profitable to transform?
3404
3405 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3406 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3407 assert(LoopPreheaderBB && "There is always a loop preheader.");
3408
3409 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3410 assert(SuccessorBB && "There is only a single successor.");
3411
3412 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3413 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
3414
3415 bool IsRightShift = XNext->getOpcode() == Instruction::LShr;
3416 Intrinsic::ID IntrID = IsRightShift ? Intrinsic::cttz : Intrinsic::ctlz;
3417 Type *Ty = X->getType();
3418 unsigned Bitwidth = Ty->getScalarSizeInBits();
3419
3420 // A right shift must be guaranteed to reach a set bit at BitPos.
3421 if (IsRightShift && !isRightShiftBitTestKnownToTerminate(
3422 X, BitPos, LoopPreheaderBB, *DL, DT)) {
3423 return false;
3424 }
3425
3428
3429 // The rewrite is considered to be unprofitable iff and only iff the
3430 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
3431 // making the loop countable, even if nothing else changes.
3433 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getTrue()});
3434 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3437 " Intrinsic is too costly, not beneficial\n");
3438 return MadeChange;
3439 }
3440 if (TTI->getArithmeticInstrCost(XNext->getOpcode(), Ty, CostKind) >
3442 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
3443 return MadeChange;
3444 }
3445
3446 // Ok, transform appears worthwhile.
3447 MadeChange = true;
3448
3449 if (!isGuaranteedNotToBeUndefOrPoison(BitPos)) {
3450 // BitMask may be computed from BitPos, Freeze BitPos so we can increase
3451 // it's use count.
3452 std::optional<BasicBlock::iterator> InsertPt = std::nullopt;
3453 if (auto *BitPosI = dyn_cast<Instruction>(BitPos))
3454 InsertPt = BitPosI->getInsertionPointAfterDef();
3455 else
3456 InsertPt = DT->getRoot()->getFirstNonPHIOrAlloca();
3457 if (!InsertPt)
3458 return false;
3459 FreezeInst *BitPosFrozen =
3460 new FreezeInst(BitPos, BitPos->getName() + ".fr", *InsertPt);
3461 BitPos->replaceUsesWithIf(BitPosFrozen, [BitPosFrozen](Use &U) {
3462 return U.getUser() != BitPosFrozen;
3463 });
3464 BitPos = BitPosFrozen;
3465 }
3466
3467 // Step 1: Compute the loop trip count.
3468
3469 Value *LoopBackedgeTakenCount;
3470 if (IsRightShift) {
3471 Value *ShiftedX = Builder.CreateLShr(X, BitPos);
3472 LoopBackedgeTakenCount = Builder.CreateIntrinsic(
3473 IntrID, Ty, {ShiftedX, /*is_zero_poison=*/Builder.getTrue()});
3474 } else {
3475 Value *LowBitMask =
3476 Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
3477 BitPos->getName() + ".lowbitmask");
3478 Value *Mask =
3479 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
3480 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
3481 Value *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
3482 IntrID, Ty, {XMasked, /*is_zero_poison=*/Builder.getTrue()},
3483 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
3484 Value *XMaskedNumActiveBits = Builder.CreateSub(
3485 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
3486 XMasked->getName() + ".numactivebits",
3487 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3488 Value *XMaskedLeadingOnePos = Builder.CreateAdd(
3489 XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
3490 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
3491 /*HasNSW=*/Bitwidth > 2);
3492
3493 LoopBackedgeTakenCount = Builder.CreateSub(
3494 BitPos, XMaskedLeadingOnePos,
3495 CurLoop->getName() + ".backedgetakencount", /*HasNUW=*/true,
3496 /*HasNSW=*/true);
3497 }
3498 // We know loop's backedge-taken count, but what's loop's trip count?
3499 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3500 Value *LoopTripCount =
3501 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3502 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3503 /*HasNSW=*/Bitwidth != 2);
3504
3505 // Step 2: Compute the recurrence's final value without a loop.
3506
3507 // NewX is always safe to compute, because `LoopBackedgeTakenCount`
3508 // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
3509 Value *NewX = IsRightShift ? Builder.CreateLShr(X, LoopBackedgeTakenCount)
3510 : Builder.CreateShl(X, LoopBackedgeTakenCount);
3511 NewX->takeName(XCurr);
3512 if (auto *I = dyn_cast<Instruction>(NewX))
3513 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3514
3515 Value *NewXNext;
3516 // Shifting X by LoopTripCount is poison if the count equals Bitwidth.
3517 // For right shifts, shift NewX by one instead. For left shifts, this can
3518 // happen when BitPos is the highest bit and X is one, so use a single
3519 // additional shift unless the larger shift is known to be safe.
3520 if (IsRightShift) {
3521 NewXNext = Builder.CreateLShr(NewX, ConstantInt::get(Ty, 1));
3522 } else if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
3523 PatternMatch::match(BitPos,
3527 Ty->getScalarSizeInBits() - 1)))) {
3528 NewXNext = Builder.CreateShl(X, LoopTripCount);
3529 } else {
3530 // Otherwise, just additionally shift by one. It's the smallest solution,
3531 // alternatively, we could check that NewX is INT_MIN (or BitPos is )
3532 // and select 0 instead.
3533 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
3534 }
3535
3536 NewXNext->takeName(XNext);
3537 if (auto *I = dyn_cast<Instruction>(NewXNext))
3538 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3539
3540 // Step 3: Adjust the successor basic block to receive the computed
3541 // recurrence's final value instead of the recurrence itself.
3542
3543 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
3544 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
3545
3546 // Step 4: Rewrite the loop into a countable form, with canonical IV.
3547
3548 // The new canonical induction variable.
3549 Builder.SetInsertPoint(LoopHeaderBB->begin());
3550 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3551
3552 // The induction itself.
3553 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3554 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3555 auto *IVNext =
3556 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
3557 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3558
3559 // The loop trip count check.
3560 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
3561 CurLoop->getName() + ".ivcheck");
3562 SmallVector<uint32_t> BranchWeights;
3563 const bool HasBranchWeights =
3564 extractBranchWeights(*LoopHeaderBB->getTerminator(), BranchWeights);
3565
3566 auto *BI = Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
3567 if (HasBranchWeights) {
3568 if (SuccessorBB == LoopHeaderBB->getTerminator()->getSuccessor(1))
3569 std::swap(BranchWeights[0], BranchWeights[1]);
3570 // We're not changing the loop profile, so we can reuse the original loop's
3571 // profile.
3572 setBranchWeights(*BI, BranchWeights,
3573 /*IsExpected=*/false);
3574 }
3575
3576 LoopHeaderBB->getTerminator()->eraseFromParent();
3577
3578 // Populate the IV PHI.
3579 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3580 IV->addIncoming(IVNext, LoopHeaderBB);
3581
3582 // Step 5: Forget the "non-computable" trip-count SCEV associated with the
3583 // loop. The loop would otherwise not be deleted even if it becomes empty.
3584
3585 SE->forgetLoop(CurLoop);
3586
3587 // Other passes will take care of actually deleting the loop if possible.
3588
3589 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
3590
3591 ++NumShiftUntilBitTest;
3592 return MadeChange;
3593}
3594
3595/// Return true if the idiom is detected in the loop.
3596///
3597/// The core idiom we are trying to detect is:
3598/// \code
3599/// entry:
3600/// <...>
3601/// %start = <...>
3602/// %extraoffset = <...>
3603/// <...>
3604/// br label %for.cond
3605///
3606/// loop:
3607/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
3608/// %nbits = add nsw i8 %iv, %extraoffset
3609/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3610/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3611/// %iv.next = add i8 %iv, 1
3612/// <...>
3613/// br i1 %val.shifted.iszero, label %end, label %loop
3614///
3615/// end:
3616/// %iv.res = phi i8 [ %iv, %loop ] <...>
3617/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3618/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3619/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3620/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3621/// <...>
3622/// \endcode
3624 Instruction *&ValShiftedIsZero,
3625 Intrinsic::ID &IntrinID, Instruction *&IV,
3626 Value *&Start, Value *&Val,
3627 const SCEV *&ExtraOffsetExpr,
3628 bool &InvertedCond) {
3630 " Performing shift-until-zero idiom detection.\n");
3631
3632 // Give up if the loop has multiple blocks or multiple backedges.
3633 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
3634 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
3635 return false;
3636 }
3637
3638 Instruction *ValShifted, *NBits, *IVNext;
3639 Value *ExtraOffset;
3640
3641 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3642 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3643 assert(LoopPreheaderBB && "There is always a loop preheader.");
3644
3645 using namespace PatternMatch;
3646
3647 // Step 1: Check if the loop backedge, condition is in desirable form.
3648
3649 CmpPredicate Pred;
3650 BasicBlock *TrueBB, *FalseBB;
3651 if (!match(LoopHeaderBB->getTerminator(),
3652 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
3653 m_BasicBlock(FalseBB))) ||
3654 !match(ValShiftedIsZero,
3655 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
3656 !ICmpInst::isEquality(Pred)) {
3657 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
3658 return false;
3659 }
3660
3661 // Step 2: Check if the comparison's operand is in desirable form.
3662 // FIXME: Val could be a one-input PHI node, which we should look past.
3663 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
3664 m_Instruction(NBits)))) {
3665 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
3666 return false;
3667 }
3668 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
3669 : Intrinsic::ctlz;
3670
3671 // Step 3: Check if the shift amount is in desirable form.
3672
3673 if (match(NBits, m_c_Add(m_Instruction(IV),
3674 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3675 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
3676 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
3677 else if (match(NBits,
3679 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3680 NBits->hasNoSignedWrap())
3681 ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
3682 else {
3683 IV = NBits;
3684 ExtraOffsetExpr = SE->getZero(NBits->getType());
3685 }
3686
3687 // Step 4: Check if the recurrence is in desirable form.
3688 auto *IVPN = dyn_cast<PHINode>(IV);
3689 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
3690 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
3691 return false;
3692 }
3693
3694 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
3695 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
3696
3697 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
3698 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
3699 return false;
3700 }
3701
3702 // Step 4: Check if the backedge's destinations are in desirable form.
3703
3705 "Should only get equality predicates here.");
3706
3707 // cmp-br is commutative, so canonicalize to a single variant.
3708 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
3709 if (InvertedCond) {
3710 Pred = ICmpInst::getInversePredicate(Pred);
3711 std::swap(TrueBB, FalseBB);
3712 }
3713
3714 // We expect to exit loop when comparison yields true,
3715 // so when it yields false we should branch back to loop header.
3716 if (FalseBB != LoopHeaderBB) {
3717 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
3718 return false;
3719 }
3720
3721 // The new, countable, loop will certainly only run a known number of
3722 // iterations, It won't be infinite. But the old loop might be infinite
3723 // under certain conditions. For logical shifts, the value will become zero
3724 // after at most bitwidth(%Val) loop iterations. However, for arithmetic
3725 // right-shift, iff the sign bit was set, the value will never become zero,
3726 // and the loop may never finish.
3727 if (ValShifted->getOpcode() == Instruction::AShr &&
3728 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
3729 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
3730 return false;
3731 }
3732
3733 // Okay, idiom checks out.
3734 return true;
3735}
3736
3737/// Look for the following loop:
3738/// \code
3739/// entry:
3740/// <...>
3741/// %start = <...>
3742/// %extraoffset = <...>
3743/// <...>
3744/// br label %loop
3745///
3746/// loop:
3747/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %loop ]
3748/// %nbits = add nsw i8 %iv, %extraoffset
3749/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3750/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3751/// %iv.next = add i8 %iv, 1
3752/// <...>
3753/// br i1 %val.shifted.iszero, label %end, label %loop
3754///
3755/// end:
3756/// %iv.res = phi i8 [ %iv, %loop ] <...>
3757/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3758/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3759/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3760/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3761/// <...>
3762/// \endcode
3763///
3764/// And transform it into:
3765/// \code
3766/// entry:
3767/// <...>
3768/// %start = <...>
3769/// %extraoffset = <...>
3770/// <...>
3771/// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
3772/// %val.numactivebits = sub i8 8, %val.numleadingzeros
3773/// %extraoffset.neg = sub i8 0, %extraoffset
3774/// %tmp = add i8 %val.numactivebits, %extraoffset.neg
3775/// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
3776/// %loop.tripcount = sub i8 %iv.final, %start
3777/// br label %loop
3778///
3779/// loop:
3780/// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
3781/// %loop.iv.next = add i8 %loop.iv, 1
3782/// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
3783/// %iv = add i8 %loop.iv, %start
3784/// <...>
3785/// br i1 %loop.ivcheck, label %end, label %loop
3786///
3787/// end:
3788/// %iv.res = phi i8 [ %iv.final, %loop ] <...>
3789/// <...>
3790/// \endcode
3791bool LoopIdiomRecognize::recognizeShiftUntilZero() {
3792 bool MadeChange = false;
3793
3794 Instruction *ValShiftedIsZero;
3795 Intrinsic::ID IntrID;
3796 Instruction *IV;
3797 Value *Start, *Val;
3798 const SCEV *ExtraOffsetExpr;
3799 bool InvertedCond;
3800 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
3801 Start, Val, ExtraOffsetExpr, InvertedCond)) {
3803 " shift-until-zero idiom detection failed.\n");
3804 return MadeChange;
3805 }
3806 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
3807
3808 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3809 // but is it profitable to transform?
3810
3811 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3812 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3813 assert(LoopPreheaderBB && "There is always a loop preheader.");
3814
3815 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3816 assert(SuccessorBB && "There is only a single successor.");
3817
3818 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3819 Builder.SetCurrentDebugLocation(IV->getDebugLoc());
3820
3821 Type *Ty = Val->getType();
3822 unsigned Bitwidth = Ty->getScalarSizeInBits();
3823
3826
3827 // The rewrite is considered to be unprofitable iff and only iff the
3828 // intrinsic we'll use are not cheap. Note that we are okay with *just*
3829 // making the loop countable, even if nothing else changes.
3831 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getFalse()});
3832 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3835 " Intrinsic is too costly, not beneficial\n");
3836 return MadeChange;
3837 }
3838
3839 // Ok, transform appears worthwhile.
3840 MadeChange = true;
3841
3842 bool OffsetIsZero = ExtraOffsetExpr->isZero();
3843
3844 // Step 1: Compute the loop's final IV value / trip count.
3845
3846 Value *ValNumLeadingZeros = Builder.CreateIntrinsic(
3847 IntrID, Ty, {Val, /*is_zero_poison=*/Builder.getFalse()},
3848 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
3849 Value *ValNumActiveBits = Builder.CreateSub(
3850 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
3851 Val->getName() + ".numactivebits", /*HasNUW=*/true,
3852 /*HasNSW=*/Bitwidth != 2);
3853
3854 SCEVExpander Expander(*SE, "loop-idiom");
3855 Expander.setInsertPoint(&*Builder.GetInsertPoint());
3856 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
3857
3858 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
3859 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
3860 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
3861 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
3862 {ValNumActiveBitsOffset, Start},
3863 /*FMFSource=*/nullptr, "iv.final");
3864
3865 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
3866 IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
3867 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
3868 // FIXME: or when the offset was `add nuw`
3869
3870 // We know loop's backedge-taken count, but what's loop's trip count?
3871 Value *LoopTripCount =
3872 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3873 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3874 /*HasNSW=*/Bitwidth != 2);
3875
3876 // Step 2: Adjust the successor basic block to receive the original
3877 // induction variable's final value instead of the orig. IV itself.
3878
3879 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
3880
3881 // Step 3: Rewrite the loop into a countable form, with canonical IV.
3882
3883 // The new canonical induction variable.
3884 Builder.SetInsertPoint(LoopHeaderBB->begin());
3885 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3886
3887 // The induction itself.
3888 Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHIIt());
3889 auto *CIVNext =
3890 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
3891 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3892
3893 // The loop trip count check.
3894 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
3895 CurLoop->getName() + ".ivcheck");
3896 auto *NewIVCheck = CIVCheck;
3897 if (InvertedCond) {
3898 NewIVCheck = Builder.CreateNot(CIVCheck);
3899 NewIVCheck->takeName(ValShiftedIsZero);
3900 }
3901
3902 // The original IV, but rebased to be an offset to the CIV.
3903 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
3904 /*HasNSW=*/true); // FIXME: what about NUW?
3905 IVDePHId->takeName(IV);
3906
3907 // The loop terminator.
3908 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3909 SmallVector<uint32_t> BranchWeights;
3910 const bool HasBranchWeights =
3911 extractBranchWeights(*LoopHeaderBB->getTerminator(), BranchWeights);
3912
3913 auto *BI = Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
3914 if (HasBranchWeights) {
3915 if (InvertedCond)
3916 std::swap(BranchWeights[0], BranchWeights[1]);
3917 // We're not changing the loop profile, so we can reuse the original loop's
3918 // profile.
3919 setBranchWeights(*BI, BranchWeights, /*IsExpected=*/false);
3920 }
3921 LoopHeaderBB->getTerminator()->eraseFromParent();
3922
3923 // Populate the IV PHI.
3924 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3925 CIV->addIncoming(CIVNext, LoopHeaderBB);
3926
3927 // Step 4: Forget the "non-computable" trip-count SCEV associated with the
3928 // loop. The loop would otherwise not be deleted even if it becomes empty.
3929
3930 SE->forgetLoop(CurLoop);
3931
3932 // Step 5: Try to cleanup the loop's body somewhat.
3933 IV->replaceAllUsesWith(IVDePHId);
3934 IV->eraseFromParent();
3935
3936 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
3937 ValShiftedIsZero->eraseFromParent();
3938
3939 // Other passes will take care of actually deleting the loop if possible.
3940
3941 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
3942
3943 ++NumShiftUntilZero;
3944 return MadeChange;
3945}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
DXIL Resource Access
This file defines the DenseMap class.
#define DEBUG_TYPE
ManagedStatic< HTTPClientCleanup > Cleanup
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Ignored)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
static Value * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
static Value * matchShiftULTCondition(CondBrInst *BI, BasicBlock *LoopEntry, APInt &Threshold)
Check if the given conditional branch is based on an unsigned less-than comparison between a variable...
static bool detectShiftUntilLessThanIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX, APInt &Threshold)
Return true if the idiom is detected in the loop.
static Value * matchCondition(CondBrInst *BI, BasicBlock *LoopEntry, bool JmpOnZero=false)
Check if the given conditional branch is based on the comparison between a variable and zero,...
static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX, Value *&BitMask, Value *&BitPos, Value *&CurrX, Instruction *&NextX)
Return true if the idiom is detected in the loop.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
static Constant * getMemSetPatternValue(Value *V, const DataLayout *DL)
getMemSetPatternValue - If a strided store of the specified value is safe to turn into a memset....
static const SCEV * getNumBytes(const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, Loop *CurLoop, const DataLayout *DL, ScalarEvolution *SE)
Compute the number of bytes as a SCEV from the backedge taken count.
static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
static Value * createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck, Intrinsic::ID IID)
static bool isRightShiftBitTestKnownToTerminate(Value *X, Value *BitPos, BasicBlock *Preheader, const DataLayout &DL, DominatorTree *DT)
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, ScalarEvolution *SE)
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
match_LoopInvariant< Ty > m_LoopInvariant(const Ty &M, const Loop *L)
Matches if the value is loop-invariant.
static bool isSameByteValueStore(Instruction &I, Value *SplatByte, Loop *L, const DataLayout &DL)
Return true if I is a (simple, loop-invariant-valued) store of the same bytewise value SplatByte.
static void deleteDeadInstruction(Instruction *I)
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define T
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1572
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
size_t size() const
Definition BasicBlock.h:461
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
PointerType * getType() const
Global values are always pointers.
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
static LLVM_ABI CRCTable genSarwateTable(const APInt &GenPoly, bool IsBigEndian)
Generate a lookup table of 256 entries by interleaving the generating polynomial.
static LLVM_ABI std::pair< APInt, APInt > genBarrettConstants(const PolynomialInfo &Info)
Auxilary entry point after analysis to generate constants for a GF(2) Barrett Reduction.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:440
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:228
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
static InstructionCost getInvalid(CostType Val=0)
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
iterator_range< user_iterator > users()
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
bool isPrecise() const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
BlockT * getHeader() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
block_iterator block_begin() const
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:696
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:199
StringRef getName() const
Definition LoopInfo.h:415
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition LoopInfo.cpp:175
This class wraps the llvm.memcpy intrinsic.
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
bool isForceInlined() const
bool isVolatile() const
Value * getValue() const
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
MaybeAlign getSourceAlign() const
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Representation for a specific memory location.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
SCEVUse getOperand(unsigned i) const
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
static constexpr auto FlagNUW
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Align getAlign() const
Value * getValueOperand()
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
unsigned getWCharSize(const Module &M) const
Returns the size of the wchar_t type in bytes.
bool has(LibFunc F) const
Tests whether a library function is available.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
@ TCC_Basic
The cost of a typical 'add' instruction.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
Definition Value.cpp:607
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:557
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Value handle that is nullable, but tries to track the Value.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:164
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ HeaderSize
Definition BTF.h:61
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
OperandType
Operands are tagged with one of the values of this enum.
Definition MCInstrDesc.h:59
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
constexpr double e
DiagnosticInfoOptimizationBase::Argument NV
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:846
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< bool, true > DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize", cl::desc("Proceed with loop idiom recognize pass, " "but do not do hash-recognize analysis."), cl::location(DisableLIRP::HashRecognize), cl::init(false), cl::ReallyHidden)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
static cl::opt< bool, true > EnableLIRPWcslen("disable-loop-idiom-wcslen", cl::desc("Proceed with loop idiom recognize pass, " "enable conversion of loop(s) to wcslen."), cl::location(DisableLIRP::Wcslen), cl::init(false), cl::ReallyHidden)
InstructionCost Cost
static cl::opt< bool, true > DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memcpy."), cl::location(DisableLIRP::Memcpy), cl::init(false), cl::ReallyHidden)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static cl::opt< bool, true > DisableLIRPStrlen("disable-loop-idiom-strlen", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to strlen."), cl::location(DisableLIRP::Strlen), cl::init(false), cl::ReallyHidden)
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
const ScalarOptions & getScalarOptions(const LLVMContext &C)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:622
LLVM_ABI Value * emitStrLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI Value * emitWcsLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the wcslen function to the builder, for the specified pointer.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
static cl::opt< bool, true > DisableLIRPMemset("disable-" DEBUG_TYPE "-memset", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memset."), cl::location(DisableLIRP::Memset), cl::init(false), cl::ReallyHidden)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
static cl::opt< bool, true > DisableLIRPAll("disable-" DEBUG_TYPE "-all", cl::desc("Options to disable Loop Idiom Recognize Pass."), cl::location(DisableLIRP::All), cl::init(false), cl::ReallyHidden)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
SCEVUseT< const SCEV * > SCEVUse
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
AAMDNodes extendTo(ssize_t Len) const
Create a new AAMDNode that describes this AAMDNode after extending it to apply to a series of bytes o...
Definition Metadata.h:847
static LLVM_ABI bool Memcpy
When true, Memcpy is disabled.
static LLVM_ABI bool Wcslen
When true, Wcslen is disabled.
static LLVM_ABI bool Strlen
When true, Strlen is disabled.
static LLVM_ABI bool HashRecognize
When true, HashRecognize is disabled.
static LLVM_ABI bool Memset
When true, Memset is disabled.
static LLVM_ABI bool All
When true, the entire pass is disabled.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
The structure that is returned when a polynomial algorithm was recognized by the analysis.
Match loop-invariant value.
match_LoopInvariant(const SubPattern_t &SP, const Loop *L)