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