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 IRBuilder<> Builder(PHTerm);
246 Builder.SetCurrentDebugLocation(DebugLoc::getDropped());
247 Value *NewICmp = Builder.CreateICmp(InvariantPredicate, NewLHS, NewRHS, "",
248 ICmp->hasSameSign());
249 NewICmp->takeName(ICmp);
250 ICmp->replaceAllUsesWith(NewICmp);
251 DeadInsts.emplace_back(ICmp);
252 RunUnswitching = true;
253 return true;
254}
255
256/// SimplifyIVUsers helper for eliminating useless
257/// comparisons against an induction variable.
258void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp,
259 Instruction *IVOperand) {
260 unsigned IVOperIdx = 0;
261 CmpPredicate Pred = ICmp->getCmpPredicate();
262 ICmpInst::Predicate OriginalPred = Pred;
263 if (IVOperand != ICmp->getOperand(0)) {
264 // Swapped
265 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
266 IVOperIdx = 1;
268 }
269
270 // Get the SCEVs for the ICmp operands (in the specific context of the
271 // current loop)
272 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
273 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
274 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
275
276 // If the condition is always true or always false in the given context,
277 // replace it with a constant value.
278 SmallVector<Instruction *, 4> Users;
279 for (Instruction *U : ICmp->users())
280 Users.push_back(U);
281 const Instruction *CtxI = findCommonDominator(Users, *DT);
282 if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
283 SE->forgetValue(ICmp);
285 DeadInsts.emplace_back(ICmp);
286 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
287 ++NumElimCmp;
288 Changed = true;
289 return;
290 }
291
292 if (makeIVComparisonInvariant(ICmp, IVOperand)) {
293 ++NumInvariantCmp;
294 Changed = true;
295 return;
296 }
297
298 if ((ICmpInst::isSigned(OriginalPred) ||
299 (ICmpInst::isUnsigned(OriginalPred) && !ICmp->hasSameSign())) &&
300 SE->haveSameSign(S, X)) {
301 // Set the samesign flag on the compare if legal, and canonicalize to
302 // the unsigned variant (for signed compares) hoping that it will open
303 // the doors for other optimizations. Note that we cannot rely on Pred
304 // here unless we check if we have swapped it.
305 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
306 LLVM_DEBUG(dbgs() << "INDVARS: Marking comparison samesign: " << *ICmp
307 << '\n');
308 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
309 ICmp->setSameSign();
310 NumSameSign++;
311 Changed = true;
312 return;
313 }
314}
315
316bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
317 // Get the SCEVs for the ICmp operands.
318 const SCEV *N = SE->getSCEV(SDiv->getOperand(0));
319 const SCEV *D = SE->getSCEV(SDiv->getOperand(1));
320
321 // Simplify unnecessary loops away.
322 const Loop *L = LI->getLoopFor(SDiv->getParent());
323 N = SE->getSCEVAtScope(N, L);
324 D = SE->getSCEVAtScope(D, L);
325
326 // Replace sdiv by udiv if both of the operands are non-negative
327 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
328 auto *UDiv = BinaryOperator::Create(
329 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
330 SDiv->getName() + ".udiv", SDiv->getIterator());
331 UDiv->setIsExact(SDiv->isExact());
332 SDiv->replaceAllUsesWith(UDiv);
333 UDiv->setDebugLoc(SDiv->getDebugLoc());
334 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
335 ++NumSimplifiedSDiv;
336 Changed = true;
337 DeadInsts.push_back(SDiv);
338 return true;
339 }
340
341 return false;
342}
343
344// i %s n -> i %u n if i >= 0 and n >= 0
345void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
346 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
347 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
348 Rem->getName() + ".urem", Rem->getIterator());
349 Rem->replaceAllUsesWith(URem);
350 URem->setDebugLoc(Rem->getDebugLoc());
351 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
352 ++NumSimplifiedSRem;
353 Changed = true;
354 DeadInsts.emplace_back(Rem);
355}
356
357// i % n --> i if i is in [0,n).
358void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
359 Rem->replaceAllUsesWith(Rem->getOperand(0));
360 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
361 ++NumElimRem;
362 Changed = true;
363 DeadInsts.emplace_back(Rem);
364}
365
366bool SimplifyIndvar::replaceRemWithNumeratorOrZeroUpdateProfiles(
367 SelectInst &SI) {
369 return false;
370 // The select instruction condition is guaranteed to evaluate to true exactly
371 // once through the duration of the loop if it is executed on every loop
372 // iteration. So we set the branch weights to be {1, LoopIterations - 1}.
373
374 // Check that the select instruction does execute every iteration.
375 BasicBlock *Latch = L->getLoopLatch();
376 if (L->getExitingBlock() != Latch || !DT->dominates(SI.getParent(), Latch))
377 return false;
378
379 // Early exits also invalidate the assumption that the select instruction is
380 // executed on every iteration, so bail here if we run into any.
381 if (L->getExitingBlock() == nullptr || L->getExitingBlock() != Latch)
382 return false;
383
384 // Construct the branch weights using the trip count.
385 unsigned TripCount = SE->getSmallConstantTripCount(L);
386 if (!TripCount)
387 TripCount = getLoopEstimatedTripCount(L).value_or(0);
388 if (!TripCount)
389 return false;
390 setBranchWeights(SI, {1, TripCount - 1}, /*IsExpected=*/false);
391 return true;
392}
393
394// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
395void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
396 auto *T = Rem->getType();
397 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
398 ICmpInst *ICmp = new ICmpInst(Rem->getIterator(), ICmpInst::ICMP_EQ, N, D);
399 ICmp->setDebugLoc(Rem->getDebugLoc());
400 SelectInst *Sel =
401 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem->getIterator());
402 Rem->replaceAllUsesWith(Sel);
403 Sel->setDebugLoc(Rem->getDebugLoc());
404 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
405 ++NumElimRem;
406 Changed = true;
407 DeadInsts.emplace_back(Rem);
408 if (!replaceRemWithNumeratorOrZeroUpdateProfiles(*Sel))
410}
411
412/// SimplifyIVUsers helper for eliminating useless remainder operations
413/// operating on an induction variable or replacing srem by urem.
414void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem,
415 Instruction *IVOperand,
416 bool IsSigned) {
417 auto *NValue = Rem->getOperand(0);
418 auto *DValue = Rem->getOperand(1);
419 // We're only interested in the case where we know something about
420 // the numerator, unless it is a srem, because we want to replace srem by urem
421 // in general.
422 bool UsedAsNumerator = IVOperand == NValue;
423 if (!UsedAsNumerator && !IsSigned)
424 return;
425
426 const SCEV *N = SE->getSCEV(NValue);
427
428 // Simplify unnecessary loops away.
429 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
430 N = SE->getSCEVAtScope(N, ICmpLoop);
431
432 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
433
434 // Do not proceed if the Numerator may be negative
435 if (!IsNumeratorNonNegative)
436 return;
437
438 const SCEV *D = SE->getSCEV(DValue);
439 D = SE->getSCEVAtScope(D, ICmpLoop);
440
441 if (UsedAsNumerator) {
442 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
443 if (SE->isKnownPredicate(LT, N, D)) {
444 replaceRemWithNumerator(Rem);
445 return;
446 }
447
448 auto *T = Rem->getType();
449 const SCEV *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
450 if (SE->isKnownPredicate(LT, NLessOne, D)) {
451 replaceRemWithNumeratorOrZero(Rem);
452 return;
453 }
454 }
455
456 // Try to replace SRem with URem, if both N and D are known non-negative.
457 // Since we had already check N, we only need to check D now
458 if (!IsSigned || !SE->isKnownNonNegative(D))
459 return;
460
461 replaceSRemWithURem(Rem);
462}
463
464bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
465 const SCEV *LHS = SE->getSCEV(WO->getLHS());
466 const SCEV *RHS = SE->getSCEV(WO->getRHS());
467 if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
468 return false;
469
470 // Proved no overflow, nuke the overflow check and, if possible, the overflow
471 // intrinsic as well.
472
473 BinaryOperator *NewResult = BinaryOperator::Create(
474 WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO->getIterator());
475
476 if (WO->isSigned())
477 NewResult->setHasNoSignedWrap(true);
478 else
479 NewResult->setHasNoUnsignedWrap(true);
480
482
483 for (auto *U : WO->users()) {
484 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
485 if (EVI->getIndices()[0] == 1)
486 EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
487 else {
488 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
489 EVI->replaceAllUsesWith(NewResult);
490 NewResult->setDebugLoc(EVI->getDebugLoc());
491 }
492 ToDelete.push_back(EVI);
493 }
494 }
495
496 for (auto *EVI : ToDelete)
497 EVI->eraseFromParent();
498
499 if (WO->use_empty())
500 WO->eraseFromParent();
501
502 Changed = true;
503 return true;
504}
505
506bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
507 const SCEV *LHS = SE->getSCEV(SI->getLHS());
508 const SCEV *RHS = SE->getSCEV(SI->getRHS());
509 if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
510 return false;
511
512 BinaryOperator *BO = BinaryOperator::Create(
513 SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI->getIterator());
514 if (SI->isSigned())
515 BO->setHasNoSignedWrap();
516 else
518
519 SI->replaceAllUsesWith(BO);
520 BO->setDebugLoc(SI->getDebugLoc());
521 DeadInsts.emplace_back(SI);
522 Changed = true;
523 return true;
524}
525
526bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
527 // It is always legal to replace
528 // icmp <pred> i32 trunc(iv), n
529 // with
530 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
531 // Or with
532 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
533 // Or with either of these if pred is an equality predicate.
534 //
535 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
536 // every comparison which uses trunc, it means that we can replace each of
537 // them with comparison of iv against sext/zext(n). We no longer need trunc
538 // after that.
539 //
540 // TODO: Should we do this if we can widen *some* comparisons, but not all
541 // of them? Sometimes it is enough to enable other optimizations, but the
542 // trunc instruction will stay in the loop.
543 Value *IV = TI->getOperand(0);
544 Type *IVTy = IV->getType();
545 const SCEV *IVSCEV = SE->getSCEV(IV);
546 const SCEV *TISCEV = SE->getSCEV(TI);
547
548 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
549 // get rid of trunc
550 bool DoesSExtCollapse = false;
551 bool DoesZExtCollapse = false;
552 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
553 DoesSExtCollapse = true;
554 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
555 DoesZExtCollapse = true;
556
557 // If neither sext nor zext does collapse, it is not profitable to do any
558 // transform. Bail.
559 if (!DoesSExtCollapse && !DoesZExtCollapse)
560 return false;
561
562 // Collect users of the trunc that look like comparisons against invariants.
563 // Bail if we find something different.
565 for (Instruction *U : TI->users()) {
566 // We don't care about users in unreachable blocks.
567 if (!DT->isReachableFromEntry(U->getParent()))
568 continue;
569 ICmpInst *ICI = dyn_cast<ICmpInst>(U);
570 if (!ICI) return false;
571 assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
572 if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
573 !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
574 return false;
575 // If we cannot get rid of trunc, bail.
576 if (ICI->isSigned() && !DoesSExtCollapse)
577 return false;
578 if (ICI->isUnsigned() && !DoesZExtCollapse)
579 return false;
580 // For equality, either signed or unsigned works.
581 ICmpUsers.push_back(ICI);
582 }
583
584 auto CanUseZExt = [&](ICmpInst *ICI) {
585 // Unsigned comparison can be widened as unsigned.
586 if (ICI->isUnsigned())
587 return true;
588 // Is it profitable to do zext?
589 if (!DoesZExtCollapse)
590 return false;
591 // For equality, we can safely zext both parts.
592 if (ICI->isEquality())
593 return true;
594 // Otherwise we can only use zext when comparing two non-negative or two
595 // negative values. But in practice, we will never pass DoesZExtCollapse
596 // check for a negative value, because zext(trunc(x)) is non-negative. So
597 // it only make sense to check for non-negativity here.
598 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
599 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
600 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
601 };
602 // Replace all comparisons against trunc with comparisons against IV.
603 for (auto *ICI : ICmpUsers) {
604 bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
605 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
606 IRBuilder<> Builder(ICI);
607 Value *Ext = nullptr;
608 // For signed/unsigned predicate, replace the old comparison with comparison
609 // of immediate IV against sext/zext of the invariant argument. If we can
610 // use either sext or zext (i.e. we are dealing with equality predicate),
611 // then prefer zext as a more canonical form.
612 // TODO: If we see a signed comparison which can be turned into unsigned,
613 // we can do it here for canonicalization purposes.
614 ICmpInst::Predicate Pred = ICI->getPredicate();
615 if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
616 if (CanUseZExt(ICI)) {
617 assert(DoesZExtCollapse && "Unprofitable zext?");
618 Ext = Builder.CreateZExt(Op1, IVTy, "zext");
620 } else {
621 assert(DoesSExtCollapse && "Unprofitable sext?");
622 Ext = Builder.CreateSExt(Op1, IVTy, "sext");
623 assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
624 }
625 bool Changed;
626 L->makeLoopInvariant(Ext, Changed);
627 (void)Changed;
628 auto *NewCmp = Builder.CreateICmp(Pred, IV, Ext);
629 ICI->replaceAllUsesWith(NewCmp);
630 DeadInsts.emplace_back(ICI);
631 }
632
633 // Trunc no longer needed.
635 DeadInsts.emplace_back(TI);
636 return true;
637}
638
639/// Eliminate an operation that consumes a simple IV and has no observable
640/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
641/// but UseInst may not be.
642bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
643 Instruction *IVOperand) {
644 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
645 eliminateIVComparison(ICmp, IVOperand);
646 return true;
647 }
648 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
649 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
650 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
651 simplifyIVRemainder(Bin, IVOperand, IsSRem);
652 return true;
653 }
654
655 if (Bin->getOpcode() == Instruction::SDiv)
656 return eliminateSDiv(Bin);
657 }
658
659 if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
660 if (eliminateOverflowIntrinsic(WO))
661 return true;
662
663 if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
664 if (eliminateSaturatingIntrinsic(SI))
665 return true;
666
667 if (auto *TI = dyn_cast<TruncInst>(UseInst))
668 if (eliminateTrunc(TI))
669 return true;
670
671 if (eliminateIdentitySCEV(UseInst, IVOperand))
672 return true;
673
674 return false;
675}
676
678 if (auto *BB = L->getLoopPreheader())
679 return BB->getTerminator();
680
681 return Hint;
682}
683
684/// Replace the UseInst with a loop invariant expression if it is safe.
685bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
686 if (!SE->isSCEVable(I->getType()))
687 return false;
688
689 // Get the symbolic expression for this instruction.
690 const SCEV *S = SE->getSCEV(I);
691
692 if (!SE->isLoopInvariant(S, L))
693 return false;
694
695 // Do not generate something ridiculous even if S is loop invariant.
696 if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
697 return false;
698
699 auto *IP = GetLoopInvariantInsertPosition(L, I);
700
701 if (!Rewriter.isSafeToExpandAt(S, IP)) {
702 LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
703 << " with non-speculable loop invariant: " << *S << '\n');
704 return false;
705 }
706
707 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
708 bool NeedToEmitLCSSAPhis = false;
709 if (!LI->replacementPreservesLCSSAForm(I, Invariant))
710 NeedToEmitLCSSAPhis = true;
711
712 I->replaceAllUsesWith(Invariant);
713 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
714 << " with loop invariant: " << *S << '\n');
715
716 if (NeedToEmitLCSSAPhis) {
717 SmallVector<Instruction *, 1> NeedsLCSSAPhis;
718 NeedsLCSSAPhis.push_back(cast<Instruction>(Invariant));
719 formLCSSAForInstructions(NeedsLCSSAPhis, *DT, *LI, SE);
720 LLVM_DEBUG(dbgs() << " INDVARS: Replacement breaks LCSSA form"
721 << " inserting LCSSA Phis" << '\n');
722 }
723 ++NumFoldedUser;
724 Changed = true;
725 DeadInsts.emplace_back(I);
726 return true;
727}
728
729/// Eliminate redundant type cast between integer and float.
730bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
731 if (UseInst->getOpcode() != CastInst::SIToFP &&
732 UseInst->getOpcode() != CastInst::UIToFP)
733 return false;
734
735 Instruction *IVOperand = cast<Instruction>(UseInst->getOperand(0));
736 // Get the symbolic expression for this instruction.
737 const SCEV *IV = SE->getSCEV(IVOperand);
738 int MaskBits;
739 if (UseInst->getOpcode() == CastInst::SIToFP)
740 MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits();
741 else
742 MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits();
743 int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
744 if (MaskBits <= DestNumSigBits) {
745 for (User *U : UseInst->users()) {
746 // Match for fptosi/fptoui of sitofp and with same type.
747 auto *CI = dyn_cast<CastInst>(U);
748 if (!CI)
749 continue;
750
751 CastInst::CastOps Opcode = CI->getOpcode();
752 if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI)
753 continue;
754
755 Value *Conv = nullptr;
756 if (IVOperand->getType() != CI->getType()) {
757 IRBuilder<> Builder(CI);
758 StringRef Name = IVOperand->getName();
759 // To match InstCombine logic, we only need sext if both fptosi and
760 // sitofp are used. If one of them is unsigned, then we can use zext.
761 if (SE->getTypeSizeInBits(IVOperand->getType()) >
762 SE->getTypeSizeInBits(CI->getType())) {
763 Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name + ".trunc");
764 } else if (Opcode == CastInst::FPToUI ||
765 UseInst->getOpcode() == CastInst::UIToFP) {
766 Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name + ".zext");
767 } else {
768 Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name + ".sext");
769 }
770 } else
771 Conv = IVOperand;
772
773 CI->replaceAllUsesWith(Conv);
774 DeadInsts.push_back(CI);
775 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI
776 << " with: " << *Conv << '\n');
777
778 ++NumFoldedUser;
779 Changed = true;
780 }
781 }
782
783 return Changed;
784}
785
786/// Eliminate any operation that SCEV can prove is an identity function.
787bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
788 Instruction *IVOperand) {
789 if (!SE->isSCEVable(UseInst->getType()) ||
790 UseInst->getType() != IVOperand->getType())
791 return false;
792
793 const SCEV *UseSCEV = SE->getSCEV(UseInst);
794 if (UseSCEV != SE->getSCEV(IVOperand))
795 return false;
796
797 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
798 // dominator tree, even if X is an operand to Y. For instance, in
799 //
800 // %iv = phi i32 {0,+,1}
801 // br %cond, label %left, label %merge
802 //
803 // left:
804 // %X = add i32 %iv, 0
805 // br label %merge
806 //
807 // merge:
808 // %M = phi (%X, %iv)
809 //
810 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
811 // %M.replaceAllUsesWith(%X) would be incorrect.
812
813 if (isa<PHINode>(UseInst))
814 // If UseInst is not a PHI node then we know that IVOperand dominates
815 // UseInst directly from the legality of SSA.
816 if (!DT || !DT->dominates(IVOperand, UseInst))
817 return false;
818
819 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
820 return false;
821
822 // Make sure the operand is not more poisonous than the instruction.
823 if (!impliesPoison(IVOperand, UseInst)) {
824 SmallVector<Instruction *> DropPoisonGeneratingInsts;
825 if (!SE->canReuseInstruction(UseSCEV, IVOperand, DropPoisonGeneratingInsts))
826 return false;
827
828 for (Instruction *I : DropPoisonGeneratingInsts)
829 I->dropPoisonGeneratingAnnotations();
830 }
831
832 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
833
834 SE->forgetValue(UseInst);
835 UseInst->replaceAllUsesWith(IVOperand);
836 ++NumElimIdentity;
837 Changed = true;
838 DeadInsts.emplace_back(UseInst);
839 return true;
840}
841
842bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO,
843 Instruction *IVOperand) {
844 return (isa<OverflowingBinaryOperator>(BO) &&
845 strengthenOverflowingOperation(BO, IVOperand)) ||
846 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand));
847}
848
849/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
850/// unsigned-overflow. Returns true if anything changed, false otherwise.
851bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
852 Instruction *IVOperand) {
855
856 if (!Flags)
857 return false;
858
863
864 // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap
865 // flags on addrecs while performing zero/sign extensions. We could call
866 // forgetValue() here to make sure those flags also propagate to any other
867 // SCEV expressions based on the addrec. However, this can have pathological
868 // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
869 return true;
870}
871
872/// Annotate the Shr in (X << IVOperand) >> C as exact using the
873/// information from the IV's range. Returns true if anything changed, false
874/// otherwise.
875bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
876 Instruction *IVOperand) {
877 if (BO->getOpcode() == Instruction::Shl) {
878 bool Changed = false;
879 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
880 for (auto *U : BO->users()) {
881 const APInt *C;
882 if (match(U,
883 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
884 match(U,
885 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
886 BinaryOperator *Shr = cast<BinaryOperator>(U);
887 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
888 Shr->setIsExact(true);
889 Changed = true;
890 }
891 }
892 }
893 return Changed;
894 }
895
896 return false;
897}
898
899/// Add all uses of Def to the current IV's worklist.
900void SimplifyIndvar::pushIVUsers(
901 Instruction *Def, SmallPtrSet<Instruction *, 16> &Simplified,
902 SmallVectorImpl<std::pair<Instruction *, Instruction *>> &SimpleIVUsers) {
903 for (Instruction *UI : Def->users()) {
904 // Avoid infinite or exponential worklist processing.
905 // Also ensure unique worklist users.
906 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
907 // self edges first.
908 if (UI == Def)
909 continue;
910
911 // Only change the current Loop, do not change the other parts (e.g. other
912 // Loops).
913 if (!L->contains(UI))
914 continue;
915
916 // Do not push the same instruction more than once.
917 if (!Simplified.insert(UI).second)
918 continue;
919
920 SimpleIVUsers.push_back(std::make_pair(UI, Def));
921 }
922}
923
924/// Return true if this instruction generates a simple SCEV
925/// expression in terms of that IV.
926///
927/// This is similar to IVUsers' isInteresting() but processes each instruction
928/// non-recursively when the operand is already known to be a simpleIVUser.
929///
930static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
931 if (!SE->isSCEVable(I->getType()))
932 return false;
933
934 // Get the symbolic expression for this instruction.
935 const SCEV *S = SE->getSCEV(I);
936
937 // Only consider affine recurrences.
939 if (AR && AR->getLoop() == L)
940 return true;
941
942 return false;
943}
944
945/// Iteratively perform simplification on a worklist of users
946/// of the specified induction variable. Each successive simplification may push
947/// more users which may themselves be candidates for simplification.
948///
949/// This algorithm does not require IVUsers analysis. Instead, it simplifies
950/// instructions in-place during analysis. Rather than rewriting induction
951/// variables bottom-up from their users, it transforms a chain of IVUsers
952/// top-down, updating the IR only when it encounters a clear optimization
953/// opportunity.
954///
955/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
956///
957void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
958 if (!SE->isSCEVable(CurrIV->getType()))
959 return;
960
961 // Instructions processed by SimplifyIndvar for CurrIV.
962 SmallPtrSet<Instruction*,16> Simplified;
963
964 // Use-def pairs if IV users waiting to be processed for CurrIV.
966
967 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
968 // called multiple times for the same LoopPhi. This is the proper thing to
969 // do for loop header phis that use each other.
970 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
971
972 while (!SimpleIVUsers.empty()) {
973 std::pair<Instruction*, Instruction*> UseOper =
974 SimpleIVUsers.pop_back_val();
975 Instruction *UseInst = UseOper.first;
976
977 // If a user of the IndVar is trivially dead, we prefer just to mark it dead
978 // rather than try to do some complex analysis or transformation (such as
979 // widening) basing on it.
980 // TODO: Propagate TLI and pass it here to handle more cases.
981 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
982 DeadInsts.emplace_back(UseInst);
983 continue;
984 }
985
986 // Bypass back edges to avoid extra work.
987 if (UseInst == CurrIV) continue;
988
989 // Try to replace UseInst with a loop invariant before any other
990 // simplifications.
991 if (replaceIVUserWithLoopInvariant(UseInst))
992 continue;
993
994 // Go further for the bitcast 'prtoint ptr to i64' or if the cast is done
995 // by truncation
997 for (Instruction *User : UseInst->users()) {
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 (Instruction *User : NarrowUse->users()) {
1742 if (User == NarrowDef)
1743 continue;
1744 if (!L->contains(User)) {
1745 auto *LCSSAPhi = cast<PHINode>(User);
1746 // Make sure there is only 1 input, so that we don't have to split
1747 // critical edges.
1748 if (LCSSAPhi->getNumOperands() != 1)
1749 return false;
1750 LCSSAPhiUsers.push_back(LCSSAPhi);
1751 continue;
1752 }
1753 if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1754 auto Pred = ICmp->getPredicate();
1755 // We have 3 types of predicates: signed, unsigned and equality
1756 // predicates. For equality, it's legal to widen icmp for either sign and
1757 // zero extend. For sign extend, we can also do so for signed predicates,
1758 // likeweise for zero extend we can widen icmp for unsigned predicates.
1759 if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(Pred))
1760 return false;
1761 if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(Pred))
1762 return false;
1763 ICmpUsers.push_back(ICmp);
1764 continue;
1765 }
1766 if (ExtKind == ExtendKind::Sign)
1767 User = dyn_cast<SExtInst>(User);
1768 else
1769 User = dyn_cast<ZExtInst>(User);
1770 if (!User || User->getType() != WideType)
1771 return false;
1772 ExtUsers.push_back(User);
1773 }
1774 if (ExtUsers.empty()) {
1775 DeadInsts.emplace_back(NarrowUse);
1776 return true;
1777 }
1778
1779 // We'll prove some facts that should be true in the context of ext users. If
1780 // there is no users, we are done now. If there are some, pick their common
1781 // dominator as context.
1782 const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1783
1784 if (!CanSignExtend && !CanZeroExtend) {
1785 // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1786 // will most likely not see it. Let's try to prove it.
1787 if (OpCode != Instruction::Add)
1788 return false;
1789 if (ExtKind != ExtendKind::Zero)
1790 return false;
1791 const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1792 const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1793 // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1794 if (NarrowUse->getOperand(0) != NarrowDef)
1795 return false;
1796 // We cannot use a different extend kind for the same operand.
1797 if (NarrowUse->getOperand(1) == NarrowDef)
1798 return false;
1799 if (!SE->isKnownNegative(RHS))
1800 return false;
1801 bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1802 SE->getNegativeSCEV(RHS), CtxI);
1803 if (!ProvedSubNUW)
1804 return false;
1805 // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1806 // neg(zext(neg(op))), which is basically sext(op).
1807 AnotherOpExtKind = ExtendKind::Sign;
1808 }
1809
1810 // Verifying that Defining operand is an AddRec
1811 const SCEV *Op1 = SE->getSCEV(WideDef);
1812 const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1813 if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1814 return false;
1815
1816 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1817
1818 // Generating a widening use instruction.
1819 Value *LHS =
1820 (NarrowUse->getOperand(0) == NarrowDef)
1821 ? WideDef
1822 : createExtendInst(NarrowUse->getOperand(0), WideType,
1823 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1824 Value *RHS =
1825 (NarrowUse->getOperand(1) == NarrowDef)
1826 ? WideDef
1827 : createExtendInst(NarrowUse->getOperand(1), WideType,
1828 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1829
1830 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1831 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1832 NarrowBO->getName());
1833 IRBuilder<> Builder(NarrowUse);
1834 Builder.Insert(WideBO);
1835 WideBO->copyIRFlags(NarrowBO);
1836 ExtendKindMap[NarrowUse] = ExtKind;
1837
1838 for (Instruction *User : ExtUsers) {
1839 assert(User->getType() == WideType && "Checked before!");
1840 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1841 << *WideBO << "\n");
1842 ++NumElimExt;
1843 User->replaceAllUsesWith(WideBO);
1844 DeadInsts.emplace_back(User);
1845 }
1846
1847 for (PHINode *User : LCSSAPhiUsers) {
1848 assert(User->getNumOperands() == 1 && "Checked before!");
1849 Builder.SetInsertPoint(User);
1850 auto *WidePN =
1851 Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1852 BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1853 assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1854 "Not a LCSSA Phi?");
1855 WidePN->addIncoming(WideBO, LoopExitingBlock);
1856 Builder.SetInsertPoint(User->getParent()->getFirstInsertionPt());
1857 auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1858 User->replaceAllUsesWith(TruncPN);
1859 DeadInsts.emplace_back(User);
1860 }
1861
1862 for (ICmpInst *User : ICmpUsers) {
1863 Builder.SetInsertPoint(User);
1864 auto ExtendedOp = [&](Value * V)->Value * {
1865 if (V == NarrowUse)
1866 return WideBO;
1867 if (ExtKind == ExtendKind::Zero)
1868 return Builder.CreateZExt(V, WideBO->getType());
1869 else
1870 return Builder.CreateSExt(V, WideBO->getType());
1871 };
1872 auto Pred = User->getPredicate();
1873 auto *LHS = ExtendedOp(User->getOperand(0));
1874 auto *RHS = ExtendedOp(User->getOperand(1));
1875 auto *WideCmp =
1876 Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1877 User->replaceAllUsesWith(WideCmp);
1878 DeadInsts.emplace_back(User);
1879 }
1880
1881 return true;
1882}
1883
1884/// Determine whether an individual user of the narrow IV can be widened. If so,
1885/// return the wide clone of the user.
1886Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU,
1887 SCEVExpander &Rewriter, PHINode *OrigPhi,
1888 PHINode *WidePhi) {
1889 assert(ExtendKindMap.count(DU.NarrowDef) &&
1890 "Should already know the kind of extension used to widen NarrowDef");
1891
1892 // This narrow use can be widened by a sext if it's non-negative or its narrow
1893 // def was widened by a sext. Same for zext.
1894 bool CanWidenBySExt =
1895 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1896 bool CanWidenByZExt =
1897 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero;
1898
1899 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1900 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1901 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1902 // For LCSSA phis, sink the truncate outside the loop.
1903 // After SimplifyCFG most loop exit targets have a single predecessor.
1904 // Otherwise fall back to a truncate within the loop.
1905 if (UsePhi->getNumOperands() != 1)
1906 truncateIVUse(DU);
1907 else {
1908 // Widening the PHI requires us to insert a trunc. The logical place
1909 // for this trunc is in the same BB as the PHI. This is not possible if
1910 // the BB is terminated by a catchswitch.
1911 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1912 return nullptr;
1913
1914 PHINode *WidePhi =
1915 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1916 UsePhi->getIterator());
1917 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1918 BasicBlock *WidePhiBB = WidePhi->getParent();
1919 IRBuilder<> Builder(WidePhiBB->getFirstInsertionPt());
1920 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType(), "",
1921 CanWidenByZExt, CanWidenBySExt);
1922 UsePhi->replaceAllUsesWith(Trunc);
1923 DeadInsts.emplace_back(UsePhi);
1924 LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1925 << *WidePhi << "\n");
1926 }
1927 return nullptr;
1928 }
1929 }
1930
1931 // Our raison d'etre! Eliminate sign and zero extension.
1932 if ((match(DU.NarrowUse, m_SExtLike(m_Value())) && CanWidenBySExt) ||
1933 (isa<ZExtInst>(DU.NarrowUse) && CanWidenByZExt)) {
1934 Value *NewDef = DU.WideDef;
1935 if (DU.NarrowUse->getType() != WideType) {
1936 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1937 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1938 if (CastWidth < IVWidth) {
1939 // The cast isn't as wide as the IV, so insert a Trunc.
1940 IRBuilder<> Builder(DU.NarrowUse);
1941 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType(), "",
1942 CanWidenByZExt, CanWidenBySExt);
1943 }
1944 else {
1945 // A wider extend was hidden behind a narrower one. This may induce
1946 // another round of IV widening in which the intermediate IV becomes
1947 // dead. It should be very rare.
1948 LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1949 << " not wide enough to subsume " << *DU.NarrowUse
1950 << "\n");
1951 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1952 NewDef = DU.NarrowUse;
1953 }
1954 }
1955 if (NewDef != DU.NarrowUse) {
1956 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1957 << " replaced by " << *DU.WideDef << "\n");
1958 ++NumElimExt;
1959 DU.NarrowUse->replaceAllUsesWith(NewDef);
1960 DeadInsts.emplace_back(DU.NarrowUse);
1961 }
1962 // Now that the extend is gone, we want to expose it's uses for potential
1963 // further simplification. We don't need to directly inform SimplifyIVUsers
1964 // of the new users, because their parent IV will be processed later as a
1965 // new loop phi. If we preserved IVUsers analysis, we would also want to
1966 // push the uses of WideDef here.
1967
1968 // No further widening is needed. The deceased [sz]ext had done it for us.
1969 return nullptr;
1970 }
1971
1972 auto tryAddRecExpansion = [&]() -> Instruction* {
1973 // Does this user itself evaluate to a recurrence after widening?
1974 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1975 if (!WideAddRec.first)
1976 WideAddRec = getWideRecurrence(DU);
1977 assert((WideAddRec.first == nullptr) ==
1978 (WideAddRec.second == ExtendKind::Unknown));
1979 if (!WideAddRec.first)
1980 return nullptr;
1981
1982 auto CanUseWideInc = [&]() {
1983 if (!WideInc)
1984 return false;
1985 // Reuse the IV increment that SCEVExpander created. Recompute flags,
1986 // unless the flags for both increments agree and it is safe to use the
1987 // ones from the original inc. In that case, the new use of the wide
1988 // increment won't be more poisonous.
1989 bool NeedToRecomputeFlags =
1991 OrigPhi, WidePhi, DU.NarrowUse, WideInc) ||
1992 DU.NarrowUse->hasNoUnsignedWrap() != WideInc->hasNoUnsignedWrap() ||
1993 DU.NarrowUse->hasNoSignedWrap() != WideInc->hasNoSignedWrap();
1994 return WideAddRec.first == WideIncExpr &&
1995 Rewriter.hoistIVInc(WideInc, DU.NarrowUse, NeedToRecomputeFlags);
1996 };
1997
1998 Instruction *WideUse = nullptr;
1999 if (CanUseWideInc())
2000 WideUse = WideInc;
2001 else {
2002 WideUse = cloneIVUser(DU, WideAddRec.first);
2003 if (!WideUse)
2004 return nullptr;
2005 }
2006 // Evaluation of WideAddRec ensured that the narrow expression could be
2007 // extended outside the loop without overflow. This suggests that the wide use
2008 // evaluates to the same expression as the extended narrow use, but doesn't
2009 // absolutely guarantee it. Hence the following failsafe check. In rare cases
2010 // where it fails, we simply throw away the newly created wide use.
2011 if (WideAddRec.first != SE->getSCEV(WideUse)) {
2012 LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
2013 << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
2014 << "\n");
2015 DeadInsts.emplace_back(WideUse);
2016 return nullptr;
2017 };
2018
2019 // if we reached this point then we are going to replace
2020 // DU.NarrowUse with WideUse. Reattach DbgValue then.
2021 replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
2022
2023 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
2024 // Returning WideUse pushes it on the worklist.
2025 return WideUse;
2026 };
2027
2028 if (auto *I = tryAddRecExpansion())
2029 return I;
2030
2031 // If use is a loop condition, try to promote the condition instead of
2032 // truncating the IV first.
2033 if (widenLoopCompare(DU))
2034 return nullptr;
2035
2036 // We are here about to generate a truncate instruction that may hurt
2037 // performance because the scalar evolution expression computed earlier
2038 // in WideAddRec.first does not indicate a polynomial induction expression.
2039 // In that case, look at the operands of the use instruction to determine
2040 // if we can still widen the use instead of truncating its operand.
2041 if (widenWithVariantUse(DU))
2042 return nullptr;
2043
2044 // This user does not evaluate to a recurrence after widening, so don't
2045 // follow it. Instead insert a Trunc to kill off the original use,
2046 // eventually isolating the original narrow IV so it can be removed.
2047 truncateIVUse(DU);
2048 return nullptr;
2049}
2050
2051/// Add eligible users of NarrowDef to NarrowIVUsers.
2052void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
2053 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
2054 bool NonNegativeDef =
2055 SE->isKnownPredicateAt(ICmpInst::ICMP_SGE, NarrowSCEV,
2056 SE->getZero(NarrowSCEV->getType()), NarrowDef);
2057 for (Instruction *NarrowUser : NarrowDef->users()) {
2058 // Handle data flow merges and bizarre phi cycles.
2059 if (!Widened.insert(NarrowUser).second)
2060 continue;
2061
2062 bool NonNegativeUse = false;
2063 if (!NonNegativeDef) {
2064 // We might have a control-dependent range information for this context.
2065 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
2066 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
2067 }
2068
2069 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
2070 NonNegativeDef || NonNegativeUse);
2071 }
2072}
2073
2074/// Process a single induction variable. First use the SCEVExpander to create a
2075/// wide induction variable that evaluates to the same recurrence as the
2076/// original narrow IV. Then use a worklist to forward traverse the narrow IV's
2077/// def-use chain. After widenIVUse has processed all interesting IV users, the
2078/// narrow IV will be isolated for removal by DeleteDeadPHIs.
2079///
2080/// It would be simpler to delete uses as they are processed, but we must avoid
2081/// invalidating SCEV expressions.
2082PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
2083 // Is this phi an induction variable?
2084 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
2085 if (!AddRec)
2086 return nullptr;
2087
2088 // Widen the induction variable expression.
2089 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign
2090 ? SE->getSignExtendExpr(AddRec, WideType)
2091 : SE->getZeroExtendExpr(AddRec, WideType);
2092
2093 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
2094 "Expect the new IV expression to preserve its type");
2095
2096 // Can the IV be extended outside the loop without overflow?
2097 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
2098 if (!AddRec || AddRec->getLoop() != L)
2099 return nullptr;
2100
2101 // An AddRec must have loop-invariant operands. Since this AddRec is
2102 // materialized by a loop header phi, the expression cannot have any post-loop
2103 // operands, so they must dominate the loop header.
2104 assert(
2105 SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
2106 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
2107 "Loop header phi recurrence inputs do not dominate the loop");
2108
2109 // Iterate over IV uses (including transitive ones) looking for IV increments
2110 // of the form 'add nsw %iv, <const>'. For each increment and each use of
2111 // the increment calculate control-dependent range information basing on
2112 // dominating conditions inside of the loop (e.g. a range check inside of the
2113 // loop). Calculated ranges are stored in PostIncRangeInfos map.
2114 //
2115 // Control-dependent range information is later used to prove that a narrow
2116 // definition is not negative (see pushNarrowIVUsers). It's difficult to do
2117 // this on demand because when pushNarrowIVUsers needs this information some
2118 // of the dominating conditions might be already widened.
2119 if (UsePostIncrementRanges)
2120 calculatePostIncRanges(OrigPhi);
2121
2122 // The rewriter provides a value for the desired IV expression. This may
2123 // either find an existing phi or materialize a new one. Either way, we
2124 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
2125 // of the phi-SCC dominates the loop entry.
2126 Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
2127 Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
2128 // If the wide phi is not a phi node, for example a cast node, like bitcast,
2129 // inttoptr, ptrtoint, just skip for now.
2130 if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
2131 // if the cast node is an inserted instruction without any user, we should
2132 // remove it to make sure the pass don't touch the function as we can not
2133 // wide the phi.
2134 if (ExpandInst->use_empty() &&
2135 Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
2136 DeadInsts.emplace_back(ExpandInst);
2137 return nullptr;
2138 }
2139
2140 // Remembering the WideIV increment generated by SCEVExpander allows
2141 // widenIVUse to reuse it when widening the narrow IV's increment. We don't
2142 // employ a general reuse mechanism because the call above is the only call to
2143 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
2144 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
2145 WideInc =
2146 dyn_cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
2147 if (WideInc) {
2148 WideIncExpr = SE->getSCEV(WideInc);
2149 // Propagate the debug location associated with the original loop
2150 // increment to the new (widened) increment.
2151 auto *OrigInc =
2152 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
2153
2154 WideInc->setDebugLoc(OrigInc->getDebugLoc());
2155 // We are replacing a narrow IV increment with a wider IV increment. If
2156 // the original (narrow) increment did not wrap, the wider increment one
2157 // should not wrap either. Set the flags to be the union of both wide
2158 // increment and original increment; this ensures we preserve flags SCEV
2159 // could infer for the wider increment. Limit this only to cases where
2160 // both increments directly increment the corresponding PHI nodes and have
2161 // the same opcode. It is not safe to re-use the flags from the original
2162 // increment, if it is more complex and SCEV expansion may have yielded a
2163 // more simplified wider increment.
2165 OrigInc, WideInc) &&
2168 WideInc->setHasNoUnsignedWrap(WideInc->hasNoUnsignedWrap() ||
2169 OrigInc->hasNoUnsignedWrap());
2170 WideInc->setHasNoSignedWrap(WideInc->hasNoSignedWrap() ||
2171 OrigInc->hasNoSignedWrap());
2172 }
2173 }
2174 }
2175
2176 LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
2177 ++NumWidened;
2178
2179 // Traverse the def-use chain using a worklist starting at the original IV.
2180 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
2181
2182 Widened.insert(OrigPhi);
2183 pushNarrowIVUsers(OrigPhi, WidePhi);
2184
2185 while (!NarrowIVUsers.empty()) {
2186 WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
2187
2188 // Process a def-use edge. This may replace the use, so don't hold a
2189 // use_iterator across it.
2190 Instruction *WideUse = widenIVUse(DU, Rewriter, OrigPhi, WidePhi);
2191
2192 // Follow all def-use edges from the previous narrow use.
2193 if (WideUse)
2194 pushNarrowIVUsers(DU.NarrowUse, WideUse);
2195
2196 // widenIVUse may have removed the def-use edge.
2197 if (DU.NarrowDef->use_empty())
2198 DeadInsts.emplace_back(DU.NarrowDef);
2199 }
2200
2201 // Attach any debug information to the new PHI.
2202 replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
2203
2204 return WidePhi;
2205}
2206
2207/// Calculates control-dependent range for the given def at the given context
2208/// by looking at dominating conditions inside of the loop
2209void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
2210 Instruction *NarrowUser) {
2211 Value *NarrowDefLHS;
2212 const APInt *NarrowDefRHS;
2213 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
2214 m_APInt(NarrowDefRHS))) ||
2215 !NarrowDefRHS->isNonNegative())
2216 return;
2217
2218 auto UpdateRangeFromCondition = [&](Value *Condition, bool TrueDest) {
2219 CmpPredicate Pred;
2220 Value *CmpRHS;
2221 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
2222 m_Value(CmpRHS))))
2223 return;
2224
2225 CmpPredicate P = TrueDest ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
2226
2227 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2228 auto CmpConstrainedLHSRange =
2230 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2232
2233 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2234 };
2235
2236 auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2237 if (!HasGuards)
2238 return;
2239
2240 for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2241 Ctx->getParent()->rend())) {
2242 Value *C = nullptr;
2244 UpdateRangeFromCondition(C, /*TrueDest=*/true);
2245 }
2246 };
2247
2248 UpdateRangeFromGuards(NarrowUser);
2249
2250 BasicBlock *NarrowUserBB = NarrowUser->getParent();
2251 // If NarrowUserBB is statically unreachable asking dominator queries may
2252 // yield surprising results. (e.g. the block may not have a dom tree node)
2253 if (!DT->isReachableFromEntry(NarrowUserBB))
2254 return;
2255
2256 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2257 L->contains(DTB->getBlock());
2258 DTB = DTB->getIDom()) {
2259 auto *BB = DTB->getBlock();
2260 auto *TI = BB->getTerminator();
2261 UpdateRangeFromGuards(TI);
2262
2263 auto *BI = dyn_cast<CondBrInst>(TI);
2264 if (!BI)
2265 continue;
2266
2267 auto *TrueSuccessor = BI->getSuccessor(0);
2268 auto *FalseSuccessor = BI->getSuccessor(1);
2269
2270 if (DT->dominates(BasicBlockEdge(BB, TrueSuccessor), NarrowUserBB))
2271 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2272
2273 if (DT->dominates(BasicBlockEdge(BB, FalseSuccessor), NarrowUserBB))
2274 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2275 }
2276}
2277
2278/// Calculates PostIncRangeInfos map for the given IV
2279void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2280 SmallPtrSet<Instruction *, 16> Visited;
2282 Worklist.push_back(OrigPhi);
2283 Visited.insert(OrigPhi);
2284
2285 while (!Worklist.empty()) {
2286 Instruction *NarrowDef = Worklist.pop_back_val();
2287
2288 for (Instruction *NarrowUser : NarrowDef->users()) {
2289 // Don't go looking outside the current loop.
2290 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2291 if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2292 continue;
2293
2294 if (!Visited.insert(NarrowUser).second)
2295 continue;
2296
2297 Worklist.push_back(NarrowUser);
2298
2299 calculatePostIncRange(NarrowDef, NarrowUser);
2300 }
2301 }
2302}
2303
2305 LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2307 unsigned &NumElimExt, unsigned &NumWidened,
2308 bool HasGuards, bool UsePostIncrementRanges) {
2309 WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2310 PHINode *WidePHI = Widener.createWideIV(Rewriter);
2311 NumElimExt = Widener.getNumElimExt();
2312 NumWidened = Widener.getNumWidened();
2313 return WidePHI;
2314}
SDValue Pred
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:170
#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:61
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:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
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.
static DebugLoc getDropped()
Definition DebugLoc.h:155
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:470
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 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 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 getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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 SCEVUse getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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 isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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:222
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:21
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:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
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
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:2493
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:881
#define N
Collect information about induction variables that are used by sign/zero extend operations.