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