LLVM 24.0.0git
SimplifyIndVar.cpp
Go to the documentation of this file.
1//===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
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 file implements induction variable simplification. It does
10// not define any actual pass or policy, but provides a single function to
11// simplify a loop's induction variables based on ScalarEvolution.
12//
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/Statistic.h"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/IRBuilder.h"
27#include "llvm/Support/Debug.h"
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "indvars"
37
38STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
39STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
40STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
41STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
43 NumSimplifiedSDiv,
44 "Number of IV signed division operations converted to unsigned division");
46 NumSimplifiedSRem,
47 "Number of IV signed remainder operations converted to unsigned remainder");
48STATISTIC(NumElimCmp, "Number of IV comparisons eliminated");
49STATISTIC(NumInvariantCmp, "Number of IV comparisons made loop invariant");
50STATISTIC(NumSameSign, "Number of IV comparisons with new samesign flags");
51
52namespace {
53 /// This is a utility for simplifying induction variables
54 /// based on ScalarEvolution. It is the primary instrument of the
55 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
56 /// other loop passes that preserve SCEV.
57 class SimplifyIndvar {
58 Loop *L;
59 LoopInfo *LI;
61 DominatorTree *DT;
63 SCEVExpander &Rewriter;
65
66 bool Changed = false;
67 bool RunUnswitching = false;
68
69 public:
70 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
72 SCEVExpander &Rewriter,
74 : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
75 DeadInsts(Dead) {
76 assert(LI && "IV simplification requires LoopInfo");
77 }
78
79 bool hasChanged() const { return Changed; }
80 bool runUnswitching() const { return RunUnswitching; }
81
82 /// Iteratively perform simplification on a worklist of users of the
83 /// specified induction variable. This is the top-level driver that applies
84 /// all simplifications to users of an IV.
85 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
86
87 void pushIVUsers(Instruction *Def,
88 SmallPtrSet<Instruction *, 16> &Simplified,
89 SmallVectorImpl<std::pair<Instruction *, Instruction *>>
90 &SimpleIVUsers);
91
92 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
93
94 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
95 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
96 bool replaceFloatIVWithIntegerIV(Instruction *UseInst);
97
98 bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
99 bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
100 bool eliminateTrunc(TruncInst *TI);
101 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
102 bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand);
103 void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand);
104 void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand,
105 bool IsSigned);
106 void replaceRemWithNumerator(BinaryOperator *Rem);
107 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
108 bool replaceRemWithNumeratorOrZeroUpdateProfiles(SelectInst &SI);
109 void replaceSRemWithURem(BinaryOperator *Rem);
110 bool eliminateSDiv(BinaryOperator *SDiv);
111 bool strengthenBinaryOp(BinaryOperator *BO, Instruction *IVOperand);
112 bool strengthenOverflowingOperation(BinaryOperator *OBO,
113 Instruction *IVOperand);
114 bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand);
115 };
116}
117
118/// Find a point in code which dominates all given instructions. We can safely
119/// assume that, whatever fact we can prove at the found point, this fact is
120/// also true for each of the given instructions.
122 DominatorTree &DT) {
123 Instruction *CommonDom = nullptr;
124 for (auto *Insn : Instructions)
125 CommonDom =
126 CommonDom ? DT.findNearestCommonDominator(CommonDom, Insn) : Insn;
127 assert(CommonDom && "Common dominator not found?");
128 return CommonDom;
129}
130
131/// Fold an IV operand into its use. This removes increments of an
132/// aligned IV when used by a instruction that ignores the low bits.
133///
134/// IVOperand is guaranteed SCEVable, but UseInst may not be.
135///
136/// Return the operand of IVOperand for this induction variable if IVOperand can
137/// be folded (in case more folding opportunities have been exposed).
138/// Otherwise return null.
139Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
140 Value *IVSrc = nullptr;
141 const unsigned OperIdx = 0;
142 const SCEV *FoldedExpr = nullptr;
143 bool MustDropExactFlag = false;
144 switch (UseInst->getOpcode()) {
145 default:
146 return nullptr;
147 case Instruction::UDiv:
148 case Instruction::LShr:
149 // We're only interested in the case where we know something about
150 // the numerator and have a constant denominator.
151 if (IVOperand != UseInst->getOperand(OperIdx) ||
152 !isa<ConstantInt>(UseInst->getOperand(1)))
153 return nullptr;
154
155 // Attempt to fold a binary operator with constant operand.
156 // e.g. ((I + 1) >> 2) => I >> 2
157 if (!isa<BinaryOperator>(IVOperand)
158 || !isa<ConstantInt>(IVOperand->getOperand(1)))
159 return nullptr;
160
161 IVSrc = IVOperand->getOperand(0);
162 // IVSrc must be the (SCEVable) IV, since the other operand is const.
163 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
164
165 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
166 if (UseInst->getOpcode() == Instruction::LShr) {
167 // Get a constant for the divisor. See createSCEV.
168 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
169 if (D->getValue().uge(BitWidth))
170 return nullptr;
171
172 D = ConstantInt::get(UseInst->getContext(),
173 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
174 }
175 const SCEV *LHS = SE->getSCEV(IVSrc);
176 const SCEV *RHS = SE->getSCEV(D);
177 FoldedExpr = SE->getUDivExpr(LHS, RHS);
178 // We might have 'exact' flag set at this point which will no longer be
179 // correct after we make the replacement.
180 if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS))
181 MustDropExactFlag = true;
182 }
183 // We have something that might fold it's operand. Compare SCEVs.
184 if (!SE->isSCEVable(UseInst->getType()))
185 return nullptr;
186
187 // Bypass the operand if SCEV can prove it has no effect.
188 if (SE->getSCEV(UseInst) != FoldedExpr)
189 return nullptr;
190
191 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
192 << " -> " << *UseInst << '\n');
193
194 UseInst->setOperand(OperIdx, IVSrc);
195 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
196
197 if (MustDropExactFlag)
198 UseInst->dropPoisonGeneratingFlags();
199
200 ++NumElimOperand;
201 Changed = true;
202 if (IVOperand->use_empty())
203 DeadInsts.emplace_back(IVOperand);
204 return IVSrc;
205}
206
207bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
208 Instruction *IVOperand) {
209 auto *Preheader = L->getLoopPreheader();
210 if (!Preheader)
211 return false;
212 unsigned IVOperIdx = 0;
213 CmpPredicate Pred = ICmp->getCmpPredicate();
214 if (IVOperand != ICmp->getOperand(0)) {
215 // Swapped
216 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
217 IVOperIdx = 1;
219 }
220
221 // Get the SCEVs for the ICmp operands (in the specific context of the
222 // current loop)
223 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
224 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
225 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
226 auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L, ICmp);
227 if (!LIP)
228 return false;
229 ICmpInst::Predicate InvariantPredicate = LIP->Pred;
230 const SCEV *InvariantLHS = LIP->LHS;
231 const SCEV *InvariantRHS = LIP->RHS;
232
233 // Do not generate something ridiculous.
234 auto *PHTerm = Preheader->getTerminator();
235 if (Rewriter.isHighCostExpansion({InvariantLHS, InvariantRHS}, L,
236 2 * SCEVCheapExpansionBudget, TTI, PHTerm) ||
237 !Rewriter.isSafeToExpandAt(InvariantLHS, PHTerm) ||
238 !Rewriter.isSafeToExpandAt(InvariantRHS, PHTerm))
239 return false;
240 auto *NewLHS =
241 Rewriter.expandCodeFor(InvariantLHS, IVOperand->getType(), PHTerm);
242 auto *NewRHS =
243 Rewriter.expandCodeFor(InvariantRHS, IVOperand->getType(), PHTerm);
244 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
245 ICmp->setPredicate(InvariantPredicate);
246 ICmp->setOperand(0, NewLHS);
247 ICmp->setOperand(1, NewRHS);
248 RunUnswitching = true;
249 return true;
250}
251
252/// SimplifyIVUsers helper for eliminating useless
253/// comparisons against an induction variable.
254void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp,
255 Instruction *IVOperand) {
256 unsigned IVOperIdx = 0;
257 CmpPredicate Pred = ICmp->getCmpPredicate();
258 ICmpInst::Predicate OriginalPred = Pred;
259 if (IVOperand != ICmp->getOperand(0)) {
260 // Swapped
261 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
262 IVOperIdx = 1;
264 }
265
266 // Get the SCEVs for the ICmp operands (in the specific context of the
267 // current loop)
268 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
269 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
270 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
271
272 // If the condition is always true or always false in the given context,
273 // replace it with a constant value.
274 SmallVector<Instruction *, 4> Users;
275 for (auto *U : ICmp->users())
276 Users.push_back(cast<Instruction>(U));
277 const Instruction *CtxI = findCommonDominator(Users, *DT);
278 if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
279 SE->forgetValue(ICmp);
281 DeadInsts.emplace_back(ICmp);
282 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
283 ++NumElimCmp;
284 Changed = true;
285 return;
286 }
287
288 if (makeIVComparisonInvariant(ICmp, IVOperand)) {
289 ++NumInvariantCmp;
290 Changed = true;
291 return;
292 }
293
294 if ((ICmpInst::isSigned(OriginalPred) ||
295 (ICmpInst::isUnsigned(OriginalPred) && !ICmp->hasSameSign())) &&
296 SE->haveSameSign(S, X)) {
297 // Set the samesign flag on the compare if legal, and canonicalize to
298 // the unsigned variant (for signed compares) hoping that it will open
299 // the doors for other optimizations. Note that we cannot rely on Pred
300 // here unless we check if we have swapped it.
301 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
302 LLVM_DEBUG(dbgs() << "INDVARS: Marking comparison samesign: " << *ICmp
303 << '\n');
304 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
305 ICmp->setSameSign();
306 NumSameSign++;
307 Changed = true;
308 return;
309 }
310}
311
312bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
313 // Get the SCEVs for the ICmp operands.
314 const SCEV *N = SE->getSCEV(SDiv->getOperand(0));
315 const SCEV *D = SE->getSCEV(SDiv->getOperand(1));
316
317 // Simplify unnecessary loops away.
318 const Loop *L = LI->getLoopFor(SDiv->getParent());
319 N = SE->getSCEVAtScope(N, L);
320 D = SE->getSCEVAtScope(D, L);
321
322 // Replace sdiv by udiv if both of the operands are non-negative
323 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
324 auto *UDiv = BinaryOperator::Create(
325 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
326 SDiv->getName() + ".udiv", SDiv->getIterator());
327 UDiv->setIsExact(SDiv->isExact());
328 SDiv->replaceAllUsesWith(UDiv);
329 UDiv->setDebugLoc(SDiv->getDebugLoc());
330 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
331 ++NumSimplifiedSDiv;
332 Changed = true;
333 DeadInsts.push_back(SDiv);
334 return true;
335 }
336
337 return false;
338}
339
340// i %s n -> i %u n if i >= 0 and n >= 0
341void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
342 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
343 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
344 Rem->getName() + ".urem", Rem->getIterator());
345 Rem->replaceAllUsesWith(URem);
346 URem->setDebugLoc(Rem->getDebugLoc());
347 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
348 ++NumSimplifiedSRem;
349 Changed = true;
350 DeadInsts.emplace_back(Rem);
351}
352
353// i % n --> i if i is in [0,n).
354void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
355 Rem->replaceAllUsesWith(Rem->getOperand(0));
356 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
357 ++NumElimRem;
358 Changed = true;
359 DeadInsts.emplace_back(Rem);
360}
361
362bool SimplifyIndvar::replaceRemWithNumeratorOrZeroUpdateProfiles(
363 SelectInst &SI) {
365 return false;
366 // The select instruction condition is guaranteed to evaluate to true exactly
367 // once through the duration of the loop if it is executed on every loop
368 // iteration. So we set the branch weights to be {1, LoopIterations - 1}.
369
370 // Check that the select instruction does execute every iteration.
371 BasicBlock *Latch = L->getLoopLatch();
372 if (L->getExitingBlock() != Latch || !DT->dominates(SI.getParent(), Latch))
373 return false;
374
375 // Early exits also invalidate the assumption that the select instruction is
376 // executed on every iteration, so bail here if we run into any.
377 if (L->getExitingBlock() == nullptr || L->getExitingBlock() != Latch)
378 return false;
379
380 // Construct the branch weights using the trip count.
381 unsigned TripCount = SE->getSmallConstantTripCount(L);
382 if (!TripCount)
383 TripCount = getLoopEstimatedTripCount(L).value_or(0);
384 if (!TripCount)
385 return false;
386 setBranchWeights(SI, {1, TripCount - 1}, /*IsExpected=*/false);
387 return true;
388}
389
390// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
391void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
392 auto *T = Rem->getType();
393 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
394 ICmpInst *ICmp = new ICmpInst(Rem->getIterator(), ICmpInst::ICMP_EQ, N, D);
395 ICmp->setDebugLoc(Rem->getDebugLoc());
396 SelectInst *Sel =
397 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem->getIterator());
398 Rem->replaceAllUsesWith(Sel);
399 Sel->setDebugLoc(Rem->getDebugLoc());
400 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
401 ++NumElimRem;
402 Changed = true;
403 DeadInsts.emplace_back(Rem);
404 if (!replaceRemWithNumeratorOrZeroUpdateProfiles(*Sel))
406}
407
408/// SimplifyIVUsers helper for eliminating useless remainder operations
409/// operating on an induction variable or replacing srem by urem.
410void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem,
411 Instruction *IVOperand,
412 bool IsSigned) {
413 auto *NValue = Rem->getOperand(0);
414 auto *DValue = Rem->getOperand(1);
415 // We're only interested in the case where we know something about
416 // the numerator, unless it is a srem, because we want to replace srem by urem
417 // in general.
418 bool UsedAsNumerator = IVOperand == NValue;
419 if (!UsedAsNumerator && !IsSigned)
420 return;
421
422 const SCEV *N = SE->getSCEV(NValue);
423
424 // Simplify unnecessary loops away.
425 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
426 N = SE->getSCEVAtScope(N, ICmpLoop);
427
428 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
429
430 // Do not proceed if the Numerator may be negative
431 if (!IsNumeratorNonNegative)
432 return;
433
434 const SCEV *D = SE->getSCEV(DValue);
435 D = SE->getSCEVAtScope(D, ICmpLoop);
436
437 if (UsedAsNumerator) {
438 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
439 if (SE->isKnownPredicate(LT, N, D)) {
440 replaceRemWithNumerator(Rem);
441 return;
442 }
443
444 auto *T = Rem->getType();
445 const SCEV *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
446 if (SE->isKnownPredicate(LT, NLessOne, D)) {
447 replaceRemWithNumeratorOrZero(Rem);
448 return;
449 }
450 }
451
452 // Try to replace SRem with URem, if both N and D are known non-negative.
453 // Since we had already check N, we only need to check D now
454 if (!IsSigned || !SE->isKnownNonNegative(D))
455 return;
456
457 replaceSRemWithURem(Rem);
458}
459
460bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
461 const SCEV *LHS = SE->getSCEV(WO->getLHS());
462 const SCEV *RHS = SE->getSCEV(WO->getRHS());
463 if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
464 return false;
465
466 // Proved no overflow, nuke the overflow check and, if possible, the overflow
467 // intrinsic as well.
468
469 BinaryOperator *NewResult = BinaryOperator::Create(
470 WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO->getIterator());
471
472 if (WO->isSigned())
473 NewResult->setHasNoSignedWrap(true);
474 else
475 NewResult->setHasNoUnsignedWrap(true);
476
478
479 for (auto *U : WO->users()) {
480 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
481 if (EVI->getIndices()[0] == 1)
482 EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
483 else {
484 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
485 EVI->replaceAllUsesWith(NewResult);
486 NewResult->setDebugLoc(EVI->getDebugLoc());
487 }
488 ToDelete.push_back(EVI);
489 }
490 }
491
492 for (auto *EVI : ToDelete)
493 EVI->eraseFromParent();
494
495 if (WO->use_empty())
496 WO->eraseFromParent();
497
498 Changed = true;
499 return true;
500}
501
502bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
503 const SCEV *LHS = SE->getSCEV(SI->getLHS());
504 const SCEV *RHS = SE->getSCEV(SI->getRHS());
505 if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
506 return false;
507
508 BinaryOperator *BO = BinaryOperator::Create(
509 SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI->getIterator());
510 if (SI->isSigned())
511 BO->setHasNoSignedWrap();
512 else
514
515 SI->replaceAllUsesWith(BO);
516 BO->setDebugLoc(SI->getDebugLoc());
517 DeadInsts.emplace_back(SI);
518 Changed = true;
519 return true;
520}
521
522bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
523 // It is always legal to replace
524 // icmp <pred> i32 trunc(iv), n
525 // with
526 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
527 // Or with
528 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
529 // Or with either of these if pred is an equality predicate.
530 //
531 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
532 // every comparison which uses trunc, it means that we can replace each of
533 // them with comparison of iv against sext/zext(n). We no longer need trunc
534 // after that.
535 //
536 // TODO: Should we do this if we can widen *some* comparisons, but not all
537 // of them? Sometimes it is enough to enable other optimizations, but the
538 // trunc instruction will stay in the loop.
539 Value *IV = TI->getOperand(0);
540 Type *IVTy = IV->getType();
541 const SCEV *IVSCEV = SE->getSCEV(IV);
542 const SCEV *TISCEV = SE->getSCEV(TI);
543
544 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
545 // get rid of trunc
546 bool DoesSExtCollapse = false;
547 bool DoesZExtCollapse = false;
548 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
549 DoesSExtCollapse = true;
550 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
551 DoesZExtCollapse = true;
552
553 // If neither sext nor zext does collapse, it is not profitable to do any
554 // transform. Bail.
555 if (!DoesSExtCollapse && !DoesZExtCollapse)
556 return false;
557
558 // Collect users of the trunc that look like comparisons against invariants.
559 // Bail if we find something different.
561 for (auto *U : TI->users()) {
562 // We don't care about users in unreachable blocks.
563 if (isa<Instruction>(U) &&
564 !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
565 continue;
566 ICmpInst *ICI = dyn_cast<ICmpInst>(U);
567 if (!ICI) return false;
568 assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
569 if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
570 !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
571 return false;
572 // If we cannot get rid of trunc, bail.
573 if (ICI->isSigned() && !DoesSExtCollapse)
574 return false;
575 if (ICI->isUnsigned() && !DoesZExtCollapse)
576 return false;
577 // For equality, either signed or unsigned works.
578 ICmpUsers.push_back(ICI);
579 }
580
581 auto CanUseZExt = [&](ICmpInst *ICI) {
582 // Unsigned comparison can be widened as unsigned.
583 if (ICI->isUnsigned())
584 return true;
585 // Is it profitable to do zext?
586 if (!DoesZExtCollapse)
587 return false;
588 // For equality, we can safely zext both parts.
589 if (ICI->isEquality())
590 return true;
591 // Otherwise we can only use zext when comparing two non-negative or two
592 // negative values. But in practice, we will never pass DoesZExtCollapse
593 // check for a negative value, because zext(trunc(x)) is non-negative. So
594 // it only make sense to check for non-negativity here.
595 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
596 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
597 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
598 };
599 // Replace all comparisons against trunc with comparisons against IV.
600 for (auto *ICI : ICmpUsers) {
601 bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
602 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
603 IRBuilder<> Builder(ICI);
604 Value *Ext = nullptr;
605 // For signed/unsigned predicate, replace the old comparison with comparison
606 // of immediate IV against sext/zext of the invariant argument. If we can
607 // use either sext or zext (i.e. we are dealing with equality predicate),
608 // then prefer zext as a more canonical form.
609 // TODO: If we see a signed comparison which can be turned into unsigned,
610 // we can do it here for canonicalization purposes.
611 ICmpInst::Predicate Pred = ICI->getPredicate();
612 if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
613 if (CanUseZExt(ICI)) {
614 assert(DoesZExtCollapse && "Unprofitable zext?");
615 Ext = Builder.CreateZExt(Op1, IVTy, "zext");
617 } else {
618 assert(DoesSExtCollapse && "Unprofitable sext?");
619 Ext = Builder.CreateSExt(Op1, IVTy, "sext");
620 assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
621 }
622 bool Changed;
623 L->makeLoopInvariant(Ext, Changed);
624 (void)Changed;
625 auto *NewCmp = Builder.CreateICmp(Pred, IV, Ext);
626 ICI->replaceAllUsesWith(NewCmp);
627 DeadInsts.emplace_back(ICI);
628 }
629
630 // Trunc no longer needed.
632 DeadInsts.emplace_back(TI);
633 return true;
634}
635
636/// Eliminate an operation that consumes a simple IV and has no observable
637/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
638/// but UseInst may not be.
639bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
640 Instruction *IVOperand) {
641 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
642 eliminateIVComparison(ICmp, IVOperand);
643 return true;
644 }
645 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
646 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
647 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
648 simplifyIVRemainder(Bin, IVOperand, IsSRem);
649 return true;
650 }
651
652 if (Bin->getOpcode() == Instruction::SDiv)
653 return eliminateSDiv(Bin);
654 }
655
656 if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
657 if (eliminateOverflowIntrinsic(WO))
658 return true;
659
660 if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
661 if (eliminateSaturatingIntrinsic(SI))
662 return true;
663
664 if (auto *TI = dyn_cast<TruncInst>(UseInst))
665 if (eliminateTrunc(TI))
666 return true;
667
668 if (eliminateIdentitySCEV(UseInst, IVOperand))
669 return true;
670
671 return false;
672}
673
675 if (auto *BB = L->getLoopPreheader())
676 return BB->getTerminator();
677
678 return Hint;
679}
680
681/// Replace the UseInst with a loop invariant expression if it is safe.
682bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
683 if (!SE->isSCEVable(I->getType()))
684 return false;
685
686 // Get the symbolic expression for this instruction.
687 const SCEV *S = SE->getSCEV(I);
688
689 if (!SE->isLoopInvariant(S, L))
690 return false;
691
692 // Do not generate something ridiculous even if S is loop invariant.
693 if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
694 return false;
695
696 auto *IP = GetLoopInvariantInsertPosition(L, I);
697
698 if (!Rewriter.isSafeToExpandAt(S, IP)) {
699 LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
700 << " with non-speculable loop invariant: " << *S << '\n');
701 return false;
702 }
703
704 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
705 bool NeedToEmitLCSSAPhis = false;
706 if (!LI->replacementPreservesLCSSAForm(I, Invariant))
707 NeedToEmitLCSSAPhis = true;
708
709 I->replaceAllUsesWith(Invariant);
710 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
711 << " with loop invariant: " << *S << '\n');
712
713 if (NeedToEmitLCSSAPhis) {
714 SmallVector<Instruction *, 1> NeedsLCSSAPhis;
715 NeedsLCSSAPhis.push_back(cast<Instruction>(Invariant));
716 formLCSSAForInstructions(NeedsLCSSAPhis, *DT, *LI, SE);
717 LLVM_DEBUG(dbgs() << " INDVARS: Replacement breaks LCSSA form"
718 << " inserting LCSSA Phis" << '\n');
719 }
720 ++NumFoldedUser;
721 Changed = true;
722 DeadInsts.emplace_back(I);
723 return true;
724}
725
726/// Eliminate redundant type cast between integer and float.
727bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
728 if (UseInst->getOpcode() != CastInst::SIToFP &&
729 UseInst->getOpcode() != CastInst::UIToFP)
730 return false;
731
732 Instruction *IVOperand = cast<Instruction>(UseInst->getOperand(0));
733 // Get the symbolic expression for this instruction.
734 const SCEV *IV = SE->getSCEV(IVOperand);
735 int MaskBits;
736 if (UseInst->getOpcode() == CastInst::SIToFP)
737 MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits();
738 else
739 MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits();
740 int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
741 if (MaskBits <= DestNumSigBits) {
742 for (User *U : UseInst->users()) {
743 // Match for fptosi/fptoui of sitofp and with same type.
744 auto *CI = dyn_cast<CastInst>(U);
745 if (!CI)
746 continue;
747
748 CastInst::CastOps Opcode = CI->getOpcode();
749 if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI)
750 continue;
751
752 Value *Conv = nullptr;
753 if (IVOperand->getType() != CI->getType()) {
754 IRBuilder<> Builder(CI);
755 StringRef Name = IVOperand->getName();
756 // To match InstCombine logic, we only need sext if both fptosi and
757 // sitofp are used. If one of them is unsigned, then we can use zext.
758 if (SE->getTypeSizeInBits(IVOperand->getType()) >
759 SE->getTypeSizeInBits(CI->getType())) {
760 Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name + ".trunc");
761 } else if (Opcode == CastInst::FPToUI ||
762 UseInst->getOpcode() == CastInst::UIToFP) {
763 Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name + ".zext");
764 } else {
765 Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name + ".sext");
766 }
767 } else
768 Conv = IVOperand;
769
770 CI->replaceAllUsesWith(Conv);
771 DeadInsts.push_back(CI);
772 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI
773 << " with: " << *Conv << '\n');
774
775 ++NumFoldedUser;
776 Changed = true;
777 }
778 }
779
780 return Changed;
781}
782
783/// Eliminate any operation that SCEV can prove is an identity function.
784bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
785 Instruction *IVOperand) {
786 if (!SE->isSCEVable(UseInst->getType()) ||
787 UseInst->getType() != IVOperand->getType())
788 return false;
789
790 const SCEV *UseSCEV = SE->getSCEV(UseInst);
791 if (UseSCEV != SE->getSCEV(IVOperand))
792 return false;
793
794 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
795 // dominator tree, even if X is an operand to Y. For instance, in
796 //
797 // %iv = phi i32 {0,+,1}
798 // br %cond, label %left, label %merge
799 //
800 // left:
801 // %X = add i32 %iv, 0
802 // br label %merge
803 //
804 // merge:
805 // %M = phi (%X, %iv)
806 //
807 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
808 // %M.replaceAllUsesWith(%X) would be incorrect.
809
810 if (isa<PHINode>(UseInst))
811 // If UseInst is not a PHI node then we know that IVOperand dominates
812 // UseInst directly from the legality of SSA.
813 if (!DT || !DT->dominates(IVOperand, UseInst))
814 return false;
815
816 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
817 return false;
818
819 // Make sure the operand is not more poisonous than the instruction.
820 if (!impliesPoison(IVOperand, UseInst)) {
821 SmallVector<Instruction *> DropPoisonGeneratingInsts;
822 if (!SE->canReuseInstruction(UseSCEV, IVOperand, DropPoisonGeneratingInsts))
823 return false;
824
825 for (Instruction *I : DropPoisonGeneratingInsts)
826 I->dropPoisonGeneratingAnnotations();
827 }
828
829 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
830
831 SE->forgetValue(UseInst);
832 UseInst->replaceAllUsesWith(IVOperand);
833 ++NumElimIdentity;
834 Changed = true;
835 DeadInsts.emplace_back(UseInst);
836 return true;
837}
838
839bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO,
840 Instruction *IVOperand) {
841 return (isa<OverflowingBinaryOperator>(BO) &&
842 strengthenOverflowingOperation(BO, IVOperand)) ||
843 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand));
844}
845
846/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
847/// unsigned-overflow. Returns true if anything changed, false otherwise.
848bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
849 Instruction *IVOperand) {
852
853 if (!Flags)
854 return false;
855
860
861 // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap
862 // flags on addrecs while performing zero/sign extensions. We could call
863 // forgetValue() here to make sure those flags also propagate to any other
864 // SCEV expressions based on the addrec. However, this can have pathological
865 // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
866 return true;
867}
868
869/// Annotate the Shr in (X << IVOperand) >> C as exact using the
870/// information from the IV's range. Returns true if anything changed, false
871/// otherwise.
872bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
873 Instruction *IVOperand) {
874 if (BO->getOpcode() == Instruction::Shl) {
875 bool Changed = false;
876 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
877 for (auto *U : BO->users()) {
878 const APInt *C;
879 if (match(U,
880 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
881 match(U,
882 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
883 BinaryOperator *Shr = cast<BinaryOperator>(U);
884 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
885 Shr->setIsExact(true);
886 Changed = true;
887 }
888 }
889 }
890 return Changed;
891 }
892
893 return false;
894}
895
896/// Add all uses of Def to the current IV's worklist.
897void SimplifyIndvar::pushIVUsers(
898 Instruction *Def, SmallPtrSet<Instruction *, 16> &Simplified,
899 SmallVectorImpl<std::pair<Instruction *, Instruction *>> &SimpleIVUsers) {
900 for (User *U : Def->users()) {
902
903 // Avoid infinite or exponential worklist processing.
904 // Also ensure unique worklist users.
905 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
906 // self edges first.
907 if (UI == Def)
908 continue;
909
910 // Only change the current Loop, do not change the other parts (e.g. other
911 // Loops).
912 if (!L->contains(UI))
913 continue;
914
915 // Do not push the same instruction more than once.
916 if (!Simplified.insert(UI).second)
917 continue;
918
919 SimpleIVUsers.push_back(std::make_pair(UI, Def));
920 }
921}
922
923/// Return true if this instruction generates a simple SCEV
924/// expression in terms of that IV.
925///
926/// This is similar to IVUsers' isInteresting() but processes each instruction
927/// non-recursively when the operand is already known to be a simpleIVUser.
928///
929static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
930 if (!SE->isSCEVable(I->getType()))
931 return false;
932
933 // Get the symbolic expression for this instruction.
934 const SCEV *S = SE->getSCEV(I);
935
936 // Only consider affine recurrences.
938 if (AR && AR->getLoop() == L)
939 return true;
940
941 return false;
942}
943
944/// Iteratively perform simplification on a worklist of users
945/// of the specified induction variable. Each successive simplification may push
946/// more users which may themselves be candidates for simplification.
947///
948/// This algorithm does not require IVUsers analysis. Instead, it simplifies
949/// instructions in-place during analysis. Rather than rewriting induction
950/// variables bottom-up from their users, it transforms a chain of IVUsers
951/// top-down, updating the IR only when it encounters a clear optimization
952/// opportunity.
953///
954/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
955///
956void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
957 if (!SE->isSCEVable(CurrIV->getType()))
958 return;
959
960 // Instructions processed by SimplifyIndvar for CurrIV.
961 SmallPtrSet<Instruction*,16> Simplified;
962
963 // Use-def pairs if IV users waiting to be processed for CurrIV.
965
966 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
967 // called multiple times for the same LoopPhi. This is the proper thing to
968 // do for loop header phis that use each other.
969 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
970
971 while (!SimpleIVUsers.empty()) {
972 std::pair<Instruction*, Instruction*> UseOper =
973 SimpleIVUsers.pop_back_val();
974 Instruction *UseInst = UseOper.first;
975
976 // If a user of the IndVar is trivially dead, we prefer just to mark it dead
977 // rather than try to do some complex analysis or transformation (such as
978 // widening) basing on it.
979 // TODO: Propagate TLI and pass it here to handle more cases.
980 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
981 DeadInsts.emplace_back(UseInst);
982 continue;
983 }
984
985 // Bypass back edges to avoid extra work.
986 if (UseInst == CurrIV) continue;
987
988 // Try to replace UseInst with a loop invariant before any other
989 // simplifications.
990 if (replaceIVUserWithLoopInvariant(UseInst))
991 continue;
992
993 // Go further for the bitcast 'prtoint ptr to i64' or if the cast is done
994 // by truncation
996 for (Use &U : UseInst->uses()) {
997 Instruction *User = cast<Instruction>(U.getUser());
998 if (replaceIVUserWithLoopInvariant(User))
999 break; // done replacing
1000 }
1001
1002 Instruction *IVOperand = UseOper.second;
1003 for (unsigned N = 0; IVOperand; ++N) {
1004 assert(N <= Simplified.size() && "runaway iteration");
1005 (void) N;
1006
1007 Value *NewOper = foldIVUser(UseInst, IVOperand);
1008 if (!NewOper)
1009 break; // done folding
1010 IVOperand = dyn_cast<Instruction>(NewOper);
1011 }
1012 if (!IVOperand)
1013 continue;
1014
1015 if (eliminateIVUser(UseInst, IVOperand)) {
1016 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1017 continue;
1018 }
1019
1020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
1021 if (strengthenBinaryOp(BO, IVOperand)) {
1022 // re-queue uses of the now modified binary operator and fall
1023 // through to the checks that remain.
1024 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1025 }
1026 }
1027
1028 // Try to use integer induction for FPToSI of float induction directly.
1029 if (replaceFloatIVWithIntegerIV(UseInst)) {
1030 // Re-queue the potentially new direct uses of IVOperand.
1031 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1032 continue;
1033 }
1034
1035 CastInst *Cast = dyn_cast<CastInst>(UseInst);
1036 if (V && Cast) {
1037 V->visitCast(Cast);
1038 continue;
1039 }
1040 if (isSimpleIVUser(UseInst, L, SE)) {
1041 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1042 }
1043 }
1044}
1045
1046namespace llvm {
1047
1049
1050/// Simplify instructions that use this induction variable
1051/// by using ScalarEvolution to analyze the IV's recurrence.
1052/// Returns a pair where the first entry indicates that the function makes
1053/// changes and the second entry indicates that it introduced new opportunities
1054/// for loop unswitching.
1055std::pair<bool, bool> simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE,
1056 DominatorTree *DT, LoopInfo *LI,
1057 const TargetTransformInfo *TTI,
1059 SCEVExpander &Rewriter, IVVisitor *V) {
1060 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
1061 Rewriter, Dead);
1062 SIV.simplifyUsers(CurrIV, V);
1063 return {SIV.hasChanged(), SIV.runUnswitching()};
1064}
1065
1066/// Simplify users of induction variables within this
1067/// loop. This does not actually change or add IVs.
1069 LoopInfo *LI, const TargetTransformInfo *TTI,
1071 SCEVExpander Rewriter(*SE, "indvars");
1072#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1073 Rewriter.setDebugType(DEBUG_TYPE);
1074#endif
1075 bool Changed = false;
1076 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1077 const auto &[C, _] =
1078 simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
1079 Changed |= C;
1080 }
1081 return Changed;
1082}
1083
1084} // namespace llvm
1085
1086namespace {
1087//===----------------------------------------------------------------------===//
1088// Widen Induction Variables - Extend the width of an IV to cover its
1089// widest uses.
1090//===----------------------------------------------------------------------===//
1091
1092class WidenIV {
1093 // Parameters
1094 PHINode *OrigPhi;
1095 Type *WideType;
1096
1097 // Context
1098 LoopInfo *LI;
1099 Loop *L;
1100 ScalarEvolution *SE;
1101 DominatorTree *DT;
1102
1103 // Does the module have any calls to the llvm.experimental.guard intrinsic
1104 // at all? If not we can avoid scanning instructions looking for guards.
1105 bool HasGuards;
1106
1107 bool UsePostIncrementRanges;
1108
1109 // Statistics
1110 unsigned NumElimExt = 0;
1111 unsigned NumWidened = 0;
1112
1113 // Result
1114 PHINode *WidePhi = nullptr;
1115 Instruction *WideInc = nullptr;
1116 const SCEV *WideIncExpr = nullptr;
1117 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1118
1119 SmallPtrSet<Instruction *,16> Widened;
1120
1121 enum class ExtendKind { Zero, Sign, Unknown };
1122
1123 // A map tracking the kind of extension used to widen each narrow IV
1124 // and narrow IV user.
1125 // Key: pointer to a narrow IV or IV user.
1126 // Value: the kind of extension used to widen this Instruction.
1127 DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
1128
1129 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1130
1131 // A map with control-dependent ranges for post increment IV uses. The key is
1132 // a pair of IV def and a use of this def denoting the context. The value is
1133 // a ConstantRange representing possible values of the def at the given
1134 // context.
1135 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1136
1137 std::optional<ConstantRange> getPostIncRangeInfo(Value *Def,
1138 Instruction *UseI) {
1139 DefUserPair Key(Def, UseI);
1140 auto It = PostIncRangeInfos.find(Key);
1141 return It == PostIncRangeInfos.end()
1142 ? std::optional<ConstantRange>(std::nullopt)
1143 : std::optional<ConstantRange>(It->second);
1144 }
1145
1146 void calculatePostIncRanges(PHINode *OrigPhi);
1147 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1148
1149 void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
1150 DefUserPair Key(Def, UseI);
1151 auto [It, Inserted] = PostIncRangeInfos.try_emplace(Key, R);
1152 if (!Inserted)
1153 It->second = R.intersectWith(It->second);
1154 }
1155
1156public:
1157 /// Record a link in the Narrow IV def-use chain along with the WideIV that
1158 /// computes the same value as the Narrow IV def. This avoids caching Use*
1159 /// pointers.
1160 struct NarrowIVDefUse {
1161 Instruction *NarrowDef = nullptr;
1162 Instruction *NarrowUse = nullptr;
1163 Instruction *WideDef = nullptr;
1164
1165 // True if the narrow def is never negative. Tracking this information lets
1166 // us use a sign extension instead of a zero extension or vice versa, when
1167 // profitable and legal.
1168 bool NeverNegative = false;
1169
1170 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1171 bool NeverNegative)
1172 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1173 NeverNegative(NeverNegative) {}
1174 };
1175
1176 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1177 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1178 bool HasGuards, bool UsePostIncrementRanges = true);
1179
1180 PHINode *createWideIV(SCEVExpander &Rewriter);
1181
1182 unsigned getNumElimExt() { return NumElimExt; };
1183 unsigned getNumWidened() { return NumWidened; };
1184
1185protected:
1186 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1187 Instruction *Use);
1188
1189 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1190 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1191 const SCEVAddRecExpr *WideAR);
1192 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1193
1194 ExtendKind getExtendKind(Instruction *I);
1195
1196 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1197
1198 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1199
1200 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1201
1202 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1203 unsigned OpCode) const;
1204
1205 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter,
1206 PHINode *OrigPhi, PHINode *WidePhi);
1207 void truncateIVUse(NarrowIVDefUse DU);
1208
1209 bool widenLoopCompare(NarrowIVDefUse DU);
1210 bool widenWithVariantUse(NarrowIVDefUse DU);
1211
1212 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1213
1214private:
1215 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
1216};
1217} // namespace
1218
1219/// Determine the insertion point for this user. By default, insert immediately
1220/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
1221/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
1222/// common dominator for the incoming blocks. A nullptr can be returned if no
1223/// viable location is found: it may happen if User is a PHI and Def only comes
1224/// to this PHI from unreachable blocks.
1226 DominatorTree *DT, LoopInfo *LI) {
1228 if (!PHI)
1229 return User;
1230
1231 Instruction *InsertPt = nullptr;
1232 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
1233 if (PHI->getIncomingValue(i) != Def)
1234 continue;
1235
1236 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
1237
1238 if (!DT->isReachableFromEntry(InsertBB))
1239 continue;
1240
1241 if (!InsertPt) {
1242 InsertPt = InsertBB->getTerminator();
1243 continue;
1244 }
1245 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
1246 InsertPt = InsertBB->getTerminator();
1247 }
1248
1249 // If we have skipped all inputs, it means that Def only comes to Phi from
1250 // unreachable blocks.
1251 if (!InsertPt)
1252 return nullptr;
1253
1254 auto *DefI = dyn_cast<Instruction>(Def);
1255 if (!DefI)
1256 return InsertPt;
1257
1258 assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
1259
1260 auto *L = LI->getLoopFor(DefI->getParent());
1261 assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
1262
1263 for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
1264 if (LI->getLoopFor(DTN->getBlock()) == L)
1265 return DTN->getBlock()->getTerminator();
1266
1267 llvm_unreachable("DefI dominates InsertPt!");
1268}
1269
1270WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1271 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1272 bool HasGuards, bool UsePostIncrementRanges)
1273 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1274 L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
1275 HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1276 DeadInsts(DI) {
1277 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
1278 ExtendKindMap[OrigPhi] = WI.IsSigned ? ExtendKind::Sign : ExtendKind::Zero;
1279}
1280
1281Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1282 bool IsSigned, Instruction *Use) {
1283 // Set the debug location and conservative insertion point.
1284 IRBuilder<> Builder(Use);
1285 // Hoist the insertion point into loop preheaders as far as possible.
1286 for (const Loop *L = LI->getLoopFor(Use->getParent());
1287 L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1288 L = L->getParentLoop())
1289 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1290
1291 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1292 Builder.CreateZExt(NarrowOper, WideType);
1293}
1294
1295/// Instantiate a wide operation to replace a narrow operation. This only needs
1296/// to handle operations that can evaluation to SCEVAddRec. It can safely return
1297/// 0 for any operation we decide not to clone.
1298Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1299 const SCEVAddRecExpr *WideAR) {
1300 unsigned Opcode = DU.NarrowUse->getOpcode();
1301 switch (Opcode) {
1302 default:
1303 return nullptr;
1304 case Instruction::Add:
1305 case Instruction::Mul:
1306 case Instruction::UDiv:
1307 case Instruction::Sub:
1308 return cloneArithmeticIVUser(DU, WideAR);
1309
1310 case Instruction::And:
1311 case Instruction::Or:
1312 case Instruction::Xor:
1313 case Instruction::Shl:
1314 case Instruction::LShr:
1315 case Instruction::AShr:
1316 return cloneBitwiseIVUser(DU);
1317 }
1318}
1319
1320Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1321 Instruction *NarrowUse = DU.NarrowUse;
1322 Instruction *NarrowDef = DU.NarrowDef;
1323 Instruction *WideDef = DU.WideDef;
1324
1325 LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1326
1327 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1328 // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1329 // invariant and will be folded or hoisted. If it actually comes from a
1330 // widened IV, it should be removed during a future call to widenIVUse.
1331 bool IsSigned = getExtendKind(NarrowDef) == ExtendKind::Sign;
1332 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1333 ? WideDef
1334 : createExtendInst(NarrowUse->getOperand(0), WideType,
1335 IsSigned, NarrowUse);
1336 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1337 ? WideDef
1338 : createExtendInst(NarrowUse->getOperand(1), WideType,
1339 IsSigned, NarrowUse);
1340
1341 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1342 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1343 NarrowBO->getName());
1344 IRBuilder<> Builder(NarrowUse);
1345 Builder.Insert(WideBO);
1346 WideBO->copyIRFlags(NarrowBO);
1347 return WideBO;
1348}
1349
1350Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1351 const SCEVAddRecExpr *WideAR) {
1352 Instruction *NarrowUse = DU.NarrowUse;
1353 Instruction *NarrowDef = DU.NarrowDef;
1354 Instruction *WideDef = DU.WideDef;
1355
1356 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1357
1358 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1359
1360 // We're trying to find X such that
1361 //
1362 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1363 //
1364 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1365 // and check using SCEV if any of them are correct.
1366
1367 // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1368 // correct solution to X.
1369 auto GuessNonIVOperand = [&](bool SignExt) {
1370 const SCEV *WideLHS;
1371 const SCEV *WideRHS;
1372
1373 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1374 if (SignExt)
1375 return SE->getSignExtendExpr(S, Ty);
1376 return SE->getZeroExtendExpr(S, Ty);
1377 };
1378
1379 if (IVOpIdx == 0) {
1380 WideLHS = SE->getSCEV(WideDef);
1381 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1382 WideRHS = GetExtend(NarrowRHS, WideType);
1383 } else {
1384 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1385 WideLHS = GetExtend(NarrowLHS, WideType);
1386 WideRHS = SE->getSCEV(WideDef);
1387 }
1388
1389 // WideUse is "WideDef `op.wide` X" as described in the comment.
1390 const SCEV *WideUse =
1391 getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
1392
1393 return WideUse == WideAR;
1394 };
1395
1396 bool SignExtend = getExtendKind(NarrowDef) == ExtendKind::Sign;
1397 if (!GuessNonIVOperand(SignExtend)) {
1398 SignExtend = !SignExtend;
1399 if (!GuessNonIVOperand(SignExtend))
1400 return nullptr;
1401 }
1402
1403 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1404 ? WideDef
1405 : createExtendInst(NarrowUse->getOperand(0), WideType,
1406 SignExtend, NarrowUse);
1407 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1408 ? WideDef
1409 : createExtendInst(NarrowUse->getOperand(1), WideType,
1410 SignExtend, NarrowUse);
1411
1412 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1413 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1414 NarrowBO->getName());
1415
1416 IRBuilder<> Builder(NarrowUse);
1417 Builder.Insert(WideBO);
1418 WideBO->copyIRFlags(NarrowBO);
1419 return WideBO;
1420}
1421
1422WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1423 auto It = ExtendKindMap.find(I);
1424 assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1425 return It->second;
1426}
1427
1428const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1429 unsigned OpCode) const {
1430 switch (OpCode) {
1431 case Instruction::Add:
1432 return SE->getAddExpr(LHS, RHS);
1433 case Instruction::Sub:
1434 return SE->getMinusSCEV(LHS, RHS);
1435 case Instruction::Mul:
1436 return SE->getMulExpr(LHS, RHS);
1437 case Instruction::UDiv:
1438 return SE->getUDivExpr(LHS, RHS);
1439 default:
1440 llvm_unreachable("Unsupported opcode.");
1441 };
1442}
1443
1444namespace {
1445
1446// Represents a interesting integer binary operation for
1447// getExtendedOperandRecurrence. This may be a shl that is being treated as a
1448// multiply or a 'or disjoint' that is being treated as 'add nsw nuw'.
1449struct BinaryOp {
1450 unsigned Opcode;
1451 std::array<Value *, 2> Operands;
1452 bool IsNSW = false;
1453 bool IsNUW = false;
1454
1455 explicit BinaryOp(Instruction *Op)
1456 : Opcode(Op->getOpcode()),
1457 Operands({Op->getOperand(0), Op->getOperand(1)}) {
1458 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
1459 IsNSW = OBO->hasNoSignedWrap();
1460 IsNUW = OBO->hasNoUnsignedWrap();
1461 }
1462 }
1463
1464 explicit BinaryOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
1465 bool IsNSW = false, bool IsNUW = false)
1466 : Opcode(Opcode), Operands({LHS, RHS}), IsNSW(IsNSW), IsNUW(IsNUW) {}
1467};
1468
1469} // end anonymous namespace
1470
1471static std::optional<BinaryOp> matchBinaryOp(Instruction *Op) {
1472 switch (Op->getOpcode()) {
1473 case Instruction::Add:
1474 case Instruction::Sub:
1475 case Instruction::Mul:
1476 return BinaryOp(Op);
1477 case Instruction::Or: {
1478 // Convert or disjoint into add nuw nsw.
1479 if (cast<PossiblyDisjointInst>(Op)->isDisjoint())
1480 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
1481 /*IsNSW=*/true, /*IsNUW=*/true);
1482 break;
1483 }
1484 case Instruction::Shl: {
1485 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
1486 unsigned BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
1487
1488 // If the shift count is not less than the bitwidth, the result of
1489 // the shift is undefined. Don't try to analyze it, because the
1490 // resolution chosen here may differ from the resolution chosen in
1491 // other parts of the compiler.
1492 if (SA->getValue().ult(BitWidth)) {
1493 // We can safely preserve the nuw flag in all cases. It's also safe to
1494 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
1495 // requires special handling. It can be preserved as long as we're not
1496 // left shifting by bitwidth - 1.
1497 bool IsNUW = Op->hasNoUnsignedWrap();
1498 bool IsNSW = Op->hasNoSignedWrap() &&
1499 (IsNUW || SA->getValue().ult(BitWidth - 1));
1500
1501 ConstantInt *X =
1502 ConstantInt::get(Op->getContext(),
1503 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
1504 return BinaryOp(Instruction::Mul, Op->getOperand(0), X, IsNSW, IsNUW);
1505 }
1506 }
1507
1508 break;
1509 }
1510 }
1511
1512 return std::nullopt;
1513}
1514
1515/// No-wrap operations can transfer sign extension of their result to their
1516/// operands. Generate the SCEV value for the widened operation without
1517/// actually modifying the IR yet. If the expression after extending the
1518/// operands is an AddRec for this loop, return the AddRec and the kind of
1519/// extension used.
1520WidenIV::WidenedRecTy
1521WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1522 auto Op = matchBinaryOp(DU.NarrowUse);
1523 if (!Op)
1524 return {nullptr, ExtendKind::Unknown};
1525
1526 assert((Op->Opcode == Instruction::Add || Op->Opcode == Instruction::Sub ||
1527 Op->Opcode == Instruction::Mul) &&
1528 "Unexpected opcode");
1529
1530 // One operand (NarrowDef) has already been extended to WideDef. Now determine
1531 // if extending the other will lead to a recurrence.
1532 const unsigned ExtendOperIdx = Op->Operands[0] == DU.NarrowDef ? 1 : 0;
1533 assert(Op->Operands[1 - ExtendOperIdx] == DU.NarrowDef && "bad DU");
1534
1535 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1536 if (!(ExtKind == ExtendKind::Sign && Op->IsNSW) &&
1537 !(ExtKind == ExtendKind::Zero && Op->IsNUW)) {
1538 ExtKind = ExtendKind::Unknown;
1539
1540 // For a non-negative NarrowDef, we can choose either type of
1541 // extension. We want to use the current extend kind if legal
1542 // (see above), and we only hit this code if we need to check
1543 // the opposite case.
1544 if (DU.NeverNegative) {
1545 if (Op->IsNSW) {
1546 ExtKind = ExtendKind::Sign;
1547 } else if (Op->IsNUW) {
1548 ExtKind = ExtendKind::Zero;
1549 }
1550 }
1551 }
1552
1553 const SCEV *ExtendOperExpr = SE->getSCEV(Op->Operands[ExtendOperIdx]);
1554 if (ExtKind == ExtendKind::Sign)
1555 ExtendOperExpr = SE->getSignExtendExpr(ExtendOperExpr, WideType);
1556 else if (ExtKind == ExtendKind::Zero)
1557 ExtendOperExpr = SE->getZeroExtendExpr(ExtendOperExpr, WideType);
1558 else
1559 return {nullptr, ExtendKind::Unknown};
1560
1561 // When creating this SCEV expr, don't apply the current operations NSW or NUW
1562 // flags. This instruction may be guarded by control flow that the no-wrap
1563 // behavior depends on. Non-control-equivalent instructions can be mapped to
1564 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1565 // semantics to those operations.
1566 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1567 const SCEV *rhs = ExtendOperExpr;
1568
1569 // Let's swap operands to the initial order for the case of non-commutative
1570 // operations, like SUB. See PR21014.
1571 if (ExtendOperIdx == 0)
1572 std::swap(lhs, rhs);
1573 const SCEVAddRecExpr *AddRec =
1574 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, Op->Opcode));
1575
1576 if (!AddRec || AddRec->getLoop() != L)
1577 return {nullptr, ExtendKind::Unknown};
1578
1579 return {AddRec, ExtKind};
1580}
1581
1582/// Is this instruction potentially interesting for further simplification after
1583/// widening it's type? In other words, can the extend be safely hoisted out of
1584/// the loop with SCEV reducing the value to a recurrence on the same loop. If
1585/// so, return the extended recurrence and the kind of extension used. Otherwise
1586/// return {nullptr, ExtendKind::Unknown}.
1587WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1588 if (!DU.NarrowUse->getType()->isIntegerTy())
1589 return {nullptr, ExtendKind::Unknown};
1590
1591 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1592 if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1593 SE->getTypeSizeInBits(WideType)) {
1594 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1595 // index. So don't follow this use.
1596 return {nullptr, ExtendKind::Unknown};
1597 }
1598
1599 const SCEV *WideExpr;
1600 ExtendKind ExtKind;
1601 if (DU.NeverNegative) {
1602 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1603 if (isa<SCEVAddRecExpr>(WideExpr))
1604 ExtKind = ExtendKind::Sign;
1605 else {
1606 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1607 ExtKind = ExtendKind::Zero;
1608 }
1609 } else if (getExtendKind(DU.NarrowDef) == ExtendKind::Sign) {
1610 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1611 ExtKind = ExtendKind::Sign;
1612 } else {
1613 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1614 ExtKind = ExtendKind::Zero;
1615 }
1616 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1617 if (!AddRec || AddRec->getLoop() != L)
1618 return {nullptr, ExtendKind::Unknown};
1619 return {AddRec, ExtKind};
1620}
1621
1622/// This IV user cannot be widened. Replace this use of the original narrow IV
1623/// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1624void WidenIV::truncateIVUse(NarrowIVDefUse DU) {
1625 auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1626 if (!InsertPt)
1627 return;
1628 LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1629 << *DU.NarrowUse << "\n");
1630 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1631 IRBuilder<> Builder(InsertPt);
1632 Value *Trunc =
1633 Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType(), "",
1634 DU.NeverNegative || ExtKind == ExtendKind::Zero,
1635 DU.NeverNegative || ExtKind == ExtendKind::Sign);
1636 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1637}
1638
1639/// If the narrow use is a compare instruction, then widen the compare
1640// (and possibly the other operand). The extend operation is hoisted into the
1641// loop preheader as far as possible.
1642bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1643 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1644 if (!Cmp)
1645 return false;
1646
1647 // We can legally widen the comparison in the following two cases:
1648 //
1649 // - The signedness of the IV extension and comparison match
1650 //
1651 // - The narrow IV is always non-negative (and thus its sign extension is
1652 // equal to its zero extension). For instance, let's say we're zero
1653 // extending %narrow for the following use
1654 //
1655 // icmp slt i32 %narrow, %val ... (A)
1656 //
1657 // and %narrow is always non-negative. Then
1658 //
1659 // (A) == icmp slt i32 sext(%narrow), sext(%val)
1660 // == icmp slt i32 zext(%narrow), sext(%val)
1661 bool IsSigned = getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1662 bool CmpPreferredSign = Cmp->hasSameSign() ? IsSigned : Cmp->isSigned();
1663 if (!DU.NeverNegative && IsSigned != CmpPreferredSign)
1664 return false;
1665
1666 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1667 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1668 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1669 assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1670
1671 // Widen the compare instruction.
1672 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1673
1674 // Widen the other operand of the compare, if necessary.
1675 if (CastWidth < IVWidth) {
1676 // If the narrow IV is always non-negative and the other operand is sext,
1677 // widen using sext so we can combine them. This works for all non-signed
1678 // comparison predicates.
1679 if (DU.NeverNegative && isa<SExtInst>(Op) && !Cmp->isSigned())
1680 CmpPreferredSign = true;
1681
1682 Value *ExtOp = createExtendInst(Op, WideType, CmpPreferredSign, Cmp);
1683 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1684 }
1685 return true;
1686}
1687
1688// The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
1689// will not work when:
1690// 1) SCEV traces back to an instruction inside the loop that SCEV can not
1691// expand, eg. add %indvar, (load %addr)
1692// 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
1693// While SCEV fails to avoid trunc, we can still try to use instruction
1694// combining approach to prove trunc is not required. This can be further
1695// extended with other instruction combining checks, but for now we handle the
1696// following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
1697//
1698// Src:
1699// %c = sub nsw %b, %indvar
1700// %d = sext %c to i64
1701// Dst:
1702// %indvar.ext1 = sext %indvar to i64
1703// %m = sext %b to i64
1704// %d = sub nsw i64 %m, %indvar.ext1
1705// Therefore, as long as the result of add/sub/mul is extended to wide type, no
1706// trunc is required regardless of how %b is generated. This pattern is common
1707// when calculating address in 64 bit architecture
1708bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1709 Instruction *NarrowUse = DU.NarrowUse;
1710 Instruction *NarrowDef = DU.NarrowDef;
1711 Instruction *WideDef = DU.WideDef;
1712
1713 // Handle the common case of add<nsw/nuw>
1714 const unsigned OpCode = NarrowUse->getOpcode();
1715 // Only Add/Sub/Mul instructions are supported.
1716 if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1717 OpCode != Instruction::Mul)
1718 return false;
1719
1720 // The operand that is not defined by NarrowDef of DU. Let's call it the
1721 // other operand.
1722 assert((NarrowUse->getOperand(0) == NarrowDef ||
1723 NarrowUse->getOperand(1) == NarrowDef) &&
1724 "bad DU");
1725
1726 const OverflowingBinaryOperator *OBO =
1728 ExtendKind ExtKind = getExtendKind(NarrowDef);
1729 bool CanSignExtend = ExtKind == ExtendKind::Sign && OBO->hasNoSignedWrap();
1730 bool CanZeroExtend = ExtKind == ExtendKind::Zero && OBO->hasNoUnsignedWrap();
1731 auto AnotherOpExtKind = ExtKind;
1732
1733 // Check that all uses are either:
1734 // - narrow def (in case of we are widening the IV increment);
1735 // - single-input LCSSA Phis;
1736 // - comparison of the chosen type;
1737 // - extend of the chosen type (raison d'etre).
1738 SmallVector<Instruction *, 4> ExtUsers;
1739 SmallVector<PHINode *, 4> LCSSAPhiUsers;
1741 for (Use &U : NarrowUse->uses()) {
1742 Instruction *User = cast<Instruction>(U.getUser());
1743 if (User == NarrowDef)
1744 continue;
1745 if (!L->contains(User)) {
1746 auto *LCSSAPhi = cast<PHINode>(User);
1747 // Make sure there is only 1 input, so that we don't have to split
1748 // critical edges.
1749 if (LCSSAPhi->getNumOperands() != 1)
1750 return false;
1751 LCSSAPhiUsers.push_back(LCSSAPhi);
1752 continue;
1753 }
1754 if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1755 auto Pred = ICmp->getPredicate();
1756 // We have 3 types of predicates: signed, unsigned and equality
1757 // predicates. For equality, it's legal to widen icmp for either sign and
1758 // zero extend. For sign extend, we can also do so for signed predicates,
1759 // likeweise for zero extend we can widen icmp for unsigned predicates.
1760 if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(Pred))
1761 return false;
1762 if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(Pred))
1763 return false;
1764 ICmpUsers.push_back(ICmp);
1765 continue;
1766 }
1767 if (ExtKind == ExtendKind::Sign)
1768 User = dyn_cast<SExtInst>(User);
1769 else
1770 User = dyn_cast<ZExtInst>(User);
1771 if (!User || User->getType() != WideType)
1772 return false;
1773 ExtUsers.push_back(User);
1774 }
1775 if (ExtUsers.empty()) {
1776 DeadInsts.emplace_back(NarrowUse);
1777 return true;
1778 }
1779
1780 // We'll prove some facts that should be true in the context of ext users. If
1781 // there is no users, we are done now. If there are some, pick their common
1782 // dominator as context.
1783 const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1784
1785 if (!CanSignExtend && !CanZeroExtend) {
1786 // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1787 // will most likely not see it. Let's try to prove it.
1788 if (OpCode != Instruction::Add)
1789 return false;
1790 if (ExtKind != ExtendKind::Zero)
1791 return false;
1792 const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1793 const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1794 // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1795 if (NarrowUse->getOperand(0) != NarrowDef)
1796 return false;
1797 // We cannot use a different extend kind for the same operand.
1798 if (NarrowUse->getOperand(1) == NarrowDef)
1799 return false;
1800 if (!SE->isKnownNegative(RHS))
1801 return false;
1802 bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1803 SE->getNegativeSCEV(RHS), CtxI);
1804 if (!ProvedSubNUW)
1805 return false;
1806 // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1807 // neg(zext(neg(op))), which is basically sext(op).
1808 AnotherOpExtKind = ExtendKind::Sign;
1809 }
1810
1811 // Verifying that Defining operand is an AddRec
1812 const SCEV *Op1 = SE->getSCEV(WideDef);
1813 const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1814 if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1815 return false;
1816
1817 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1818
1819 // Generating a widening use instruction.
1820 Value *LHS =
1821 (NarrowUse->getOperand(0) == NarrowDef)
1822 ? WideDef
1823 : createExtendInst(NarrowUse->getOperand(0), WideType,
1824 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1825 Value *RHS =
1826 (NarrowUse->getOperand(1) == NarrowDef)
1827 ? WideDef
1828 : createExtendInst(NarrowUse->getOperand(1), WideType,
1829 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1830
1831 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1832 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1833 NarrowBO->getName());
1834 IRBuilder<> Builder(NarrowUse);
1835 Builder.Insert(WideBO);
1836 WideBO->copyIRFlags(NarrowBO);
1837 ExtendKindMap[NarrowUse] = ExtKind;
1838
1839 for (Instruction *User : ExtUsers) {
1840 assert(User->getType() == WideType && "Checked before!");
1841 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1842 << *WideBO << "\n");
1843 ++NumElimExt;
1844 User->replaceAllUsesWith(WideBO);
1845 DeadInsts.emplace_back(User);
1846 }
1847
1848 for (PHINode *User : LCSSAPhiUsers) {
1849 assert(User->getNumOperands() == 1 && "Checked before!");
1850 Builder.SetInsertPoint(User);
1851 auto *WidePN =
1852 Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1853 BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1854 assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1855 "Not a LCSSA Phi?");
1856 WidePN->addIncoming(WideBO, LoopExitingBlock);
1857 Builder.SetInsertPoint(User->getParent()->getFirstInsertionPt());
1858 auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1859 User->replaceAllUsesWith(TruncPN);
1860 DeadInsts.emplace_back(User);
1861 }
1862
1863 for (ICmpInst *User : ICmpUsers) {
1864 Builder.SetInsertPoint(User);
1865 auto ExtendedOp = [&](Value * V)->Value * {
1866 if (V == NarrowUse)
1867 return WideBO;
1868 if (ExtKind == ExtendKind::Zero)
1869 return Builder.CreateZExt(V, WideBO->getType());
1870 else
1871 return Builder.CreateSExt(V, WideBO->getType());
1872 };
1873 auto Pred = User->getPredicate();
1874 auto *LHS = ExtendedOp(User->getOperand(0));
1875 auto *RHS = ExtendedOp(User->getOperand(1));
1876 auto *WideCmp =
1877 Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1878 User->replaceAllUsesWith(WideCmp);
1879 DeadInsts.emplace_back(User);
1880 }
1881
1882 return true;
1883}
1884
1885/// Determine whether an individual user of the narrow IV can be widened. If so,
1886/// return the wide clone of the user.
1887Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU,
1888 SCEVExpander &Rewriter, PHINode *OrigPhi,
1889 PHINode *WidePhi) {
1890 assert(ExtendKindMap.count(DU.NarrowDef) &&
1891 "Should already know the kind of extension used to widen NarrowDef");
1892
1893 // This narrow use can be widened by a sext if it's non-negative or its narrow
1894 // def was widened by a sext. Same for zext.
1895 bool CanWidenBySExt =
1896 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1897 bool CanWidenByZExt =
1898 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero;
1899
1900 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1901 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1902 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1903 // For LCSSA phis, sink the truncate outside the loop.
1904 // After SimplifyCFG most loop exit targets have a single predecessor.
1905 // Otherwise fall back to a truncate within the loop.
1906 if (UsePhi->getNumOperands() != 1)
1907 truncateIVUse(DU);
1908 else {
1909 // Widening the PHI requires us to insert a trunc. The logical place
1910 // for this trunc is in the same BB as the PHI. This is not possible if
1911 // the BB is terminated by a catchswitch.
1912 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1913 return nullptr;
1914
1915 PHINode *WidePhi =
1916 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1917 UsePhi->getIterator());
1918 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1919 BasicBlock *WidePhiBB = WidePhi->getParent();
1920 IRBuilder<> Builder(WidePhiBB->getFirstInsertionPt());
1921 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType(), "",
1922 CanWidenByZExt, CanWidenBySExt);
1923 UsePhi->replaceAllUsesWith(Trunc);
1924 DeadInsts.emplace_back(UsePhi);
1925 LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1926 << *WidePhi << "\n");
1927 }
1928 return nullptr;
1929 }
1930 }
1931
1932 // Our raison d'etre! Eliminate sign and zero extension.
1933 if ((match(DU.NarrowUse, m_SExtLike(m_Value())) && CanWidenBySExt) ||
1934 (isa<ZExtInst>(DU.NarrowUse) && CanWidenByZExt)) {
1935 Value *NewDef = DU.WideDef;
1936 if (DU.NarrowUse->getType() != WideType) {
1937 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1938 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1939 if (CastWidth < IVWidth) {
1940 // The cast isn't as wide as the IV, so insert a Trunc.
1941 IRBuilder<> Builder(DU.NarrowUse);
1942 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType(), "",
1943 CanWidenByZExt, CanWidenBySExt);
1944 }
1945 else {
1946 // A wider extend was hidden behind a narrower one. This may induce
1947 // another round of IV widening in which the intermediate IV becomes
1948 // dead. It should be very rare.
1949 LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1950 << " not wide enough to subsume " << *DU.NarrowUse
1951 << "\n");
1952 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1953 NewDef = DU.NarrowUse;
1954 }
1955 }
1956 if (NewDef != DU.NarrowUse) {
1957 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1958 << " replaced by " << *DU.WideDef << "\n");
1959 ++NumElimExt;
1960 DU.NarrowUse->replaceAllUsesWith(NewDef);
1961 DeadInsts.emplace_back(DU.NarrowUse);
1962 }
1963 // Now that the extend is gone, we want to expose it's uses for potential
1964 // further simplification. We don't need to directly inform SimplifyIVUsers
1965 // of the new users, because their parent IV will be processed later as a
1966 // new loop phi. If we preserved IVUsers analysis, we would also want to
1967 // push the uses of WideDef here.
1968
1969 // No further widening is needed. The deceased [sz]ext had done it for us.
1970 return nullptr;
1971 }
1972
1973 auto tryAddRecExpansion = [&]() -> Instruction* {
1974 // Does this user itself evaluate to a recurrence after widening?
1975 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1976 if (!WideAddRec.first)
1977 WideAddRec = getWideRecurrence(DU);
1978 assert((WideAddRec.first == nullptr) ==
1979 (WideAddRec.second == ExtendKind::Unknown));
1980 if (!WideAddRec.first)
1981 return nullptr;
1982
1983 auto CanUseWideInc = [&]() {
1984 if (!WideInc)
1985 return false;
1986 // Reuse the IV increment that SCEVExpander created. Recompute flags,
1987 // unless the flags for both increments agree and it is safe to use the
1988 // ones from the original inc. In that case, the new use of the wide
1989 // increment won't be more poisonous.
1990 bool NeedToRecomputeFlags =
1992 OrigPhi, WidePhi, DU.NarrowUse, WideInc) ||
1993 DU.NarrowUse->hasNoUnsignedWrap() != WideInc->hasNoUnsignedWrap() ||
1994 DU.NarrowUse->hasNoSignedWrap() != WideInc->hasNoSignedWrap();
1995 return WideAddRec.first == WideIncExpr &&
1996 Rewriter.hoistIVInc(WideInc, DU.NarrowUse, NeedToRecomputeFlags);
1997 };
1998
1999 Instruction *WideUse = nullptr;
2000 if (CanUseWideInc())
2001 WideUse = WideInc;
2002 else {
2003 WideUse = cloneIVUser(DU, WideAddRec.first);
2004 if (!WideUse)
2005 return nullptr;
2006 }
2007 // Evaluation of WideAddRec ensured that the narrow expression could be
2008 // extended outside the loop without overflow. This suggests that the wide use
2009 // evaluates to the same expression as the extended narrow use, but doesn't
2010 // absolutely guarantee it. Hence the following failsafe check. In rare cases
2011 // where it fails, we simply throw away the newly created wide use.
2012 if (WideAddRec.first != SE->getSCEV(WideUse)) {
2013 LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
2014 << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
2015 << "\n");
2016 DeadInsts.emplace_back(WideUse);
2017 return nullptr;
2018 };
2019
2020 // if we reached this point then we are going to replace
2021 // DU.NarrowUse with WideUse. Reattach DbgValue then.
2022 replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
2023
2024 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
2025 // Returning WideUse pushes it on the worklist.
2026 return WideUse;
2027 };
2028
2029 if (auto *I = tryAddRecExpansion())
2030 return I;
2031
2032 // If use is a loop condition, try to promote the condition instead of
2033 // truncating the IV first.
2034 if (widenLoopCompare(DU))
2035 return nullptr;
2036
2037 // We are here about to generate a truncate instruction that may hurt
2038 // performance because the scalar evolution expression computed earlier
2039 // in WideAddRec.first does not indicate a polynomial induction expression.
2040 // In that case, look at the operands of the use instruction to determine
2041 // if we can still widen the use instead of truncating its operand.
2042 if (widenWithVariantUse(DU))
2043 return nullptr;
2044
2045 // This user does not evaluate to a recurrence after widening, so don't
2046 // follow it. Instead insert a Trunc to kill off the original use,
2047 // eventually isolating the original narrow IV so it can be removed.
2048 truncateIVUse(DU);
2049 return nullptr;
2050}
2051
2052/// Add eligible users of NarrowDef to NarrowIVUsers.
2053void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
2054 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
2055 bool NonNegativeDef =
2056 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
2057 SE->getZero(NarrowSCEV->getType()));
2058 for (User *U : NarrowDef->users()) {
2059 Instruction *NarrowUser = cast<Instruction>(U);
2060
2061 // Handle data flow merges and bizarre phi cycles.
2062 if (!Widened.insert(NarrowUser).second)
2063 continue;
2064
2065 bool NonNegativeUse = false;
2066 if (!NonNegativeDef) {
2067 // We might have a control-dependent range information for this context.
2068 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
2069 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
2070 }
2071
2072 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
2073 NonNegativeDef || NonNegativeUse);
2074 }
2075}
2076
2077/// Process a single induction variable. First use the SCEVExpander to create a
2078/// wide induction variable that evaluates to the same recurrence as the
2079/// original narrow IV. Then use a worklist to forward traverse the narrow IV's
2080/// def-use chain. After widenIVUse has processed all interesting IV users, the
2081/// narrow IV will be isolated for removal by DeleteDeadPHIs.
2082///
2083/// It would be simpler to delete uses as they are processed, but we must avoid
2084/// invalidating SCEV expressions.
2085PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
2086 // Is this phi an induction variable?
2087 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
2088 if (!AddRec)
2089 return nullptr;
2090
2091 // Widen the induction variable expression.
2092 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign
2093 ? SE->getSignExtendExpr(AddRec, WideType)
2094 : SE->getZeroExtendExpr(AddRec, WideType);
2095
2096 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
2097 "Expect the new IV expression to preserve its type");
2098
2099 // Can the IV be extended outside the loop without overflow?
2100 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
2101 if (!AddRec || AddRec->getLoop() != L)
2102 return nullptr;
2103
2104 // An AddRec must have loop-invariant operands. Since this AddRec is
2105 // materialized by a loop header phi, the expression cannot have any post-loop
2106 // operands, so they must dominate the loop header.
2107 assert(
2108 SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
2109 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
2110 "Loop header phi recurrence inputs do not dominate the loop");
2111
2112 // Iterate over IV uses (including transitive ones) looking for IV increments
2113 // of the form 'add nsw %iv, <const>'. For each increment and each use of
2114 // the increment calculate control-dependent range information basing on
2115 // dominating conditions inside of the loop (e.g. a range check inside of the
2116 // loop). Calculated ranges are stored in PostIncRangeInfos map.
2117 //
2118 // Control-dependent range information is later used to prove that a narrow
2119 // definition is not negative (see pushNarrowIVUsers). It's difficult to do
2120 // this on demand because when pushNarrowIVUsers needs this information some
2121 // of the dominating conditions might be already widened.
2122 if (UsePostIncrementRanges)
2123 calculatePostIncRanges(OrigPhi);
2124
2125 // The rewriter provides a value for the desired IV expression. This may
2126 // either find an existing phi or materialize a new one. Either way, we
2127 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
2128 // of the phi-SCC dominates the loop entry.
2129 Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
2130 Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
2131 // If the wide phi is not a phi node, for example a cast node, like bitcast,
2132 // inttoptr, ptrtoint, just skip for now.
2133 if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
2134 // if the cast node is an inserted instruction without any user, we should
2135 // remove it to make sure the pass don't touch the function as we can not
2136 // wide the phi.
2137 if (ExpandInst->use_empty() &&
2138 Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
2139 DeadInsts.emplace_back(ExpandInst);
2140 return nullptr;
2141 }
2142
2143 // Remembering the WideIV increment generated by SCEVExpander allows
2144 // widenIVUse to reuse it when widening the narrow IV's increment. We don't
2145 // employ a general reuse mechanism because the call above is the only call to
2146 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
2147 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
2148 WideInc =
2149 dyn_cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
2150 if (WideInc) {
2151 WideIncExpr = SE->getSCEV(WideInc);
2152 // Propagate the debug location associated with the original loop
2153 // increment to the new (widened) increment.
2154 auto *OrigInc =
2155 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
2156
2157 WideInc->setDebugLoc(OrigInc->getDebugLoc());
2158 // We are replacing a narrow IV increment with a wider IV increment. If
2159 // the original (narrow) increment did not wrap, the wider increment one
2160 // should not wrap either. Set the flags to be the union of both wide
2161 // increment and original increment; this ensures we preserve flags SCEV
2162 // could infer for the wider increment. Limit this only to cases where
2163 // both increments directly increment the corresponding PHI nodes and have
2164 // the same opcode. It is not safe to re-use the flags from the original
2165 // increment, if it is more complex and SCEV expansion may have yielded a
2166 // more simplified wider increment.
2168 OrigInc, WideInc) &&
2171 WideInc->setHasNoUnsignedWrap(WideInc->hasNoUnsignedWrap() ||
2172 OrigInc->hasNoUnsignedWrap());
2173 WideInc->setHasNoSignedWrap(WideInc->hasNoSignedWrap() ||
2174 OrigInc->hasNoSignedWrap());
2175 }
2176 }
2177 }
2178
2179 LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
2180 ++NumWidened;
2181
2182 // Traverse the def-use chain using a worklist starting at the original IV.
2183 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
2184
2185 Widened.insert(OrigPhi);
2186 pushNarrowIVUsers(OrigPhi, WidePhi);
2187
2188 while (!NarrowIVUsers.empty()) {
2189 WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
2190
2191 // Process a def-use edge. This may replace the use, so don't hold a
2192 // use_iterator across it.
2193 Instruction *WideUse = widenIVUse(DU, Rewriter, OrigPhi, WidePhi);
2194
2195 // Follow all def-use edges from the previous narrow use.
2196 if (WideUse)
2197 pushNarrowIVUsers(DU.NarrowUse, WideUse);
2198
2199 // widenIVUse may have removed the def-use edge.
2200 if (DU.NarrowDef->use_empty())
2201 DeadInsts.emplace_back(DU.NarrowDef);
2202 }
2203
2204 // Attach any debug information to the new PHI.
2205 replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
2206
2207 return WidePhi;
2208}
2209
2210/// Calculates control-dependent range for the given def at the given context
2211/// by looking at dominating conditions inside of the loop
2212void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
2213 Instruction *NarrowUser) {
2214 Value *NarrowDefLHS;
2215 const APInt *NarrowDefRHS;
2216 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
2217 m_APInt(NarrowDefRHS))) ||
2218 !NarrowDefRHS->isNonNegative())
2219 return;
2220
2221 auto UpdateRangeFromCondition = [&](Value *Condition, bool TrueDest) {
2222 CmpPredicate Pred;
2223 Value *CmpRHS;
2224 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
2225 m_Value(CmpRHS))))
2226 return;
2227
2228 CmpPredicate P = TrueDest ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
2229
2230 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2231 auto CmpConstrainedLHSRange =
2233 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2235
2236 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2237 };
2238
2239 auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2240 if (!HasGuards)
2241 return;
2242
2243 for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2244 Ctx->getParent()->rend())) {
2245 Value *C = nullptr;
2247 UpdateRangeFromCondition(C, /*TrueDest=*/true);
2248 }
2249 };
2250
2251 UpdateRangeFromGuards(NarrowUser);
2252
2253 BasicBlock *NarrowUserBB = NarrowUser->getParent();
2254 // If NarrowUserBB is statically unreachable asking dominator queries may
2255 // yield surprising results. (e.g. the block may not have a dom tree node)
2256 if (!DT->isReachableFromEntry(NarrowUserBB))
2257 return;
2258
2259 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2260 L->contains(DTB->getBlock());
2261 DTB = DTB->getIDom()) {
2262 auto *BB = DTB->getBlock();
2263 auto *TI = BB->getTerminator();
2264 UpdateRangeFromGuards(TI);
2265
2266 auto *BI = dyn_cast<CondBrInst>(TI);
2267 if (!BI)
2268 continue;
2269
2270 auto *TrueSuccessor = BI->getSuccessor(0);
2271 auto *FalseSuccessor = BI->getSuccessor(1);
2272
2273 if (DT->dominates(BasicBlockEdge(BB, TrueSuccessor), NarrowUserBB))
2274 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2275
2276 if (DT->dominates(BasicBlockEdge(BB, FalseSuccessor), NarrowUserBB))
2277 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2278 }
2279}
2280
2281/// Calculates PostIncRangeInfos map for the given IV
2282void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2283 SmallPtrSet<Instruction *, 16> Visited;
2285 Worklist.push_back(OrigPhi);
2286 Visited.insert(OrigPhi);
2287
2288 while (!Worklist.empty()) {
2289 Instruction *NarrowDef = Worklist.pop_back_val();
2290
2291 for (Use &U : NarrowDef->uses()) {
2292 auto *NarrowUser = cast<Instruction>(U.getUser());
2293
2294 // Don't go looking outside the current loop.
2295 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2296 if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2297 continue;
2298
2299 if (!Visited.insert(NarrowUser).second)
2300 continue;
2301
2302 Worklist.push_back(NarrowUser);
2303
2304 calculatePostIncRange(NarrowDef, NarrowUser);
2305 }
2306 }
2307}
2308
2310 LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2312 unsigned &NumElimExt, unsigned &NumWidened,
2313 bool HasGuards, bool UsePostIncrementRanges) {
2314 WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2315 PHINode *WidePHI = Widener.createWideIV(Rewriter);
2316 NumElimExt = Widener.getNumElimExt();
2317 NumWidened = Widener.getNumWidened();
2318 return WidePHI;
2319}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define DEBUG_TYPE
#define _
iv Induction Variable Users
Definition IVUsers.cpp:48
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
This file contains the declarations for profiling metadata utility functions.
SI Fold Operands
static Instruction * GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint)
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE)
Return true if this instruction generates a simple SCEV expression in terms of that IV.
static Instruction * findCommonDominator(ArrayRef< Instruction * > Instructions, DominatorTree &DT)
Find a point in code which dominates all given instructions.
static Instruction * getInsertPointForUses(Instruction *User, Value *Def, DominatorTree *DT, LoopInfo *LI)
Determine the insertion point for this user.
static std::optional< BinaryOp > matchBinaryOp(Instruction *Op)
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
TTI::PartialReductionExtendKind ExtendKind
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI bool isSigned() const
Whether the intrinsic is signed or unsigned.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
bool isSigned() const
Definition InstrTypes.h:993
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
bool isUnsigned() const
Definition InstrTypes.h:999
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
LLVM_ABI unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
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.
bool hasSameSign() const
An icmp instruction, which can be marked as "samesign", indicating that the two operands have the sam...
void setSameSign(bool B=true)
CmpPredicate getCmpPredicate() const
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Interface for visiting interesting IV users that are recognized but not simplified by this utility.
virtual void anchor()
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
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.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:466
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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.
This node represents a polynomial recurrence on the trip count of the specified loop.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class uses information about analyze scalars to rewrite expressions in canonical form.
static LLVM_ABI bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
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.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
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 Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:227
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
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
@ User
could "use" a pointer
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
@ Unknown
Not known to have no common set bits.
@ Dead
Unused definition.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ BinaryOp
One of the operands is a binary op.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI PHINode * createWideIV(const WideIVInfo &WI, LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, unsigned &NumElimExt, unsigned &NumWidened, bool HasGuards, bool UsePostIncrementRanges)
Widen Induction Variables - Extend the width of an IV to cover its widest uses.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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...
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2446
LLVM_ABI std::pair< bool, bool > simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead, SCEVExpander &Rewriter, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
TargetTransformInfo TTI
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition LCSSA.cpp:328
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
Collect information about induction variables that are used by sign/zero extend operations.