LLVM 24.0.0git
IndVarSimplify.cpp
Go to the documentation of this file.
1//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
10// computations derived from them) into simpler forms suitable for subsequent
11// analysis and transformation.
12//
13// If the trip count of a loop is computable, this pass also makes the following
14// changes:
15// 1. The exit condition for the loop is canonicalized to compare the
16// induction value against the exit value. This turns loops like:
17// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
18// 2. Any use outside of the loop of an expression derived from the indvar
19// is changed to compute the derived value outside of the loop, eliminating
20// the dependence on the exit value of the induction variable. If the only
21// purpose of the loop is to compute the exit value of some derived
22// expression, this transformation will make the loop dead.
23//
24//===----------------------------------------------------------------------===//
25
27#include "ScalarOptions.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Intrinsics.h"
58#include "llvm/IR/PassManager.h"
60#include "llvm/IR/Type.h"
61#include "llvm/IR/Use.h"
62#include "llvm/IR/User.h"
63#include "llvm/IR/Value.h"
64#include "llvm/IR/ValueHandle.h"
66#include "llvm/Support/Debug.h"
75#include <cassert>
76#include <cstdint>
77#include <utility>
78
79using namespace llvm;
80using namespace PatternMatch;
81using namespace SCEVPatternMatch;
82
83#define DEBUG_TYPE "indvars"
84
85STATISTIC(NumWidened , "Number of indvars widened");
86STATISTIC(NumReplaced , "Number of exit values replaced");
87STATISTIC(NumLFTR , "Number of loop exit tests replaced");
88STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
89STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
90
91namespace {
92
93class IndVarSimplify {
94 const ScalarOptions &Opts;
95 LoopInfo *LI;
97 DominatorTree *DT;
98 const DataLayout &DL;
101 std::unique_ptr<MemorySSAUpdater> MSSAU;
102
104 bool WidenIndVars;
105
106 bool RunUnswitching = false;
107
108 bool handleFloatingPointIV(Loop *L, PHINode *PH);
109 bool rewriteNonIntegerIVs(Loop *L);
110
111 bool simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
112 /// Try to improve our exit conditions by converting condition from signed
113 /// to unsigned or rotating computation out of the loop.
114 /// (See inline comment about why this is duplicated from simplifyAndExtend)
115 bool canonicalizeExitCondition(Loop *L);
116 /// Try to eliminate loop exits based on analyzeable exit counts
117 bool optimizeLoopExits(Loop *L, SCEVExpander &Rewriter);
118 /// Try to form loop invariant tests for loop exits by changing how many
119 /// iterations of the loop run when that is unobservable.
120 bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
121
122 bool rewriteFirstIterationLoopExitValues(Loop *L);
123
124 bool linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
125 const SCEV *ExitCount,
126 PHINode *IndVar, SCEVExpander &Rewriter);
127
128 bool sinkUnusedInvariants(Loop *L);
129
130public:
131 IndVarSimplify(const ScalarOptions &Opts, LoopInfo *LI, ScalarEvolution *SE,
132 DominatorTree *DT, const DataLayout &DL,
134 MemorySSA *MSSA, bool WidenIndVars)
135 : Opts(Opts), LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI),
136 WidenIndVars(WidenIndVars) {
137 if (MSSA)
138 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
139 }
140
141 bool run(Loop *L);
142
143 bool runUnswitching() const { return RunUnswitching; }
144};
145
146} // end anonymous namespace
147
148//===----------------------------------------------------------------------===//
149// rewriteNonIntegerIVs and helpers. Prefer integer IVs.
150//===----------------------------------------------------------------------===//
151
152/// Convert APF to an integer, if possible.
153static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
154 bool isExact = false;
155 // See if we can convert this to an int64_t
156 uint64_t UIntVal;
157 if (APF.convertToInteger(MutableArrayRef(UIntVal), 64, true,
158 APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
159 !isExact)
160 return false;
161 IntVal = UIntVal;
162 return true;
163}
164
165/// Ensure we stay within the bounds of fp values that can be represented as
166/// integers without gaps, which are 2^24 and 2^53 for IEEE-754 single and
167/// double precision respectively (both on negative and positive side).
168static bool isRepresentableAsExactInteger(const APFloat &FPVal,
169 int64_t IntVal) {
170 const auto &FltSema = FPVal.getSemantics();
171 if (!APFloat::isIEEELikeFP(FltSema))
172 return false;
173 return isUIntN(APFloat::semanticsPrecision(FltSema), AbsoluteValue(IntVal));
174}
175
176/// Represents a floating-point induction variable pattern that may be
177/// convertible to integer form.
190
191/// Represents the integer values for a converted IV.
198
200 switch (FPPred) {
203 return CmpInst::ICMP_EQ;
206 return CmpInst::ICMP_NE;
209 return CmpInst::ICMP_SGT;
212 return CmpInst::ICMP_SGE;
215 return CmpInst::ICMP_SLT;
218 return CmpInst::ICMP_SLE;
219 default:
221 }
222}
223
224/// Analyze a PN to determine whether it represents a simple floating-point
225/// induction variable, with constant fp init, increment, and exit values.
226///
227/// Returns a FloatingPointIV struct if matched, std::nullopt otherwise.
228static std::optional<FloatingPointIV>
230 // Identify incoming and backedge for the PN.
231 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
232 unsigned BackEdge = IncomingEdge ^ 1;
233
234 // Check incoming value.
235 auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
236 if (!InitValueVal)
237 return std::nullopt;
238
239 // Check IV increment. Reject this PN if increment operation is not
240 // an add or increment value can not be represented by an integer.
241 auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
242 if (!Incr || Incr->getOpcode() != Instruction::FAdd)
243 return std::nullopt;
244
245 // If this is not an add of the PHI with a constantfp, or if the constant fp
246 // is not an integer, bail out.
247 auto *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
248 if (!IncValueVal || Incr->getOperand(0) != PN)
249 return std::nullopt;
250
251 // Check Incr uses. One user is PN and the other user is an exit condition
252 // used by the conditional terminator.
253 // TODO: Should relax this, so as to allow any `fpext` that may occur.
254 if (!Incr->hasNUses(2))
255 return std::nullopt;
256
257 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
258 // only used by a branch, we can't transform it.
259 auto It = llvm::find_if(Incr->users(),
260 [](const User *U) { return isa<FCmpInst>(U); });
261 if (It == Incr->users().end())
262 return std::nullopt;
263
264 FCmpInst *Compare = cast<FCmpInst>(*It);
265 if (!Compare->hasOneUse())
266 return std::nullopt;
267
268 // We need to verify that the branch actually controls the iteration count
269 // of the loop. If not, the new IV can overflow and no one will notice.
270 // The branch block must be in the loop and one of the successors must be out
271 // of the loop.
272 auto *BI = dyn_cast<CondBrInst>(Compare->user_back());
273 if (!BI)
274 return std::nullopt;
275
276 if (!L->contains(BI->getParent()) ||
277 (L->contains(BI->getSuccessor(0)) && L->contains(BI->getSuccessor(1))))
278 return std::nullopt;
279
280 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
281 // transform it.
282 auto *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
283 if (!ExitValueVal)
284 return std::nullopt;
285
286 return FloatingPointIV(InitValueVal->getValueAPF(),
287 IncValueVal->getValueAPF(),
288 ExitValueVal->getValueAPF(), Compare, Incr);
289}
290
291/// Ensure that the floating-point IV can be converted to a semantics-preserving
292/// signed 32-bit integer IV.
293///
294/// Returns a IntegerIV struct if possible, std::nullopt otherwise.
295static std::optional<IntegerIV>
297 // Convert floating-point predicate to integer.
298 auto NewPred = getIntegerPredicate(FPIV.Compare->getPredicate());
299 if (NewPred == CmpInst::BAD_ICMP_PREDICATE)
300 return std::nullopt;
301
302 // Convert APFloat values to signed integers.
303 int64_t InitValue, IncrValue, ExitValue;
304 if (!ConvertToSInt(FPIV.InitValue, InitValue) ||
305 !ConvertToSInt(FPIV.IncrValue, IncrValue) ||
306 !ConvertToSInt(FPIV.ExitValue, ExitValue))
307 return std::nullopt;
308
309 // Bail out if integers cannot be represented exactly.
310 if (!isRepresentableAsExactInteger(FPIV.InitValue, InitValue) ||
312 return std::nullopt;
313
314 // We convert the floating point induction variable to a signed i32 value if
315 // we can. This is only safe if the comparison will not overflow in a way that
316 // won't be trapped by the integer equivalent operations. Check for this now.
317 // TODO: We could use i64 if it is native and the range requires it.
318
319 // The start/stride/exit values must all fit in signed i32.
320 if (!isInt<32>(InitValue) || !isInt<32>(IncrValue) || !isInt<32>(ExitValue))
321 return std::nullopt;
322
323 // If not actually striding (add x, 0.0), avoid touching the code.
324 if (IncrValue == 0)
325 return std::nullopt;
326
327 // Positive and negative strides have different safety conditions.
328 if (IncrValue > 0) {
329 // If we have a positive stride, we require the init to be less than the
330 // exit value.
331 if (InitValue >= ExitValue)
332 return std::nullopt;
333
334 uint32_t Range = uint32_t(ExitValue - InitValue);
335 // Check for infinite loop, either:
336 // while (i <= Exit) or until (i > Exit)
337 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
338 if (++Range == 0)
339 return std::nullopt; // Range overflows.
340 }
341
342 unsigned Leftover = Range % uint32_t(IncrValue);
343
344 // If this is an equality comparison, we require that the strided value
345 // exactly land on the exit value, otherwise the IV condition will wrap
346 // around and do things the fp IV wouldn't.
347 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
348 Leftover != 0)
349 return std::nullopt;
350
351 // If the stride would wrap around the i32 before exiting, we can't
352 // transform the IV.
353 if (Leftover != 0 && int32_t(ExitValue + IncrValue) < ExitValue)
354 return std::nullopt;
355 } else {
356 // If we have a negative stride, we require the init to be greater than the
357 // exit value.
358 if (InitValue <= ExitValue)
359 return std::nullopt;
360
361 uint32_t Range = uint32_t(InitValue - ExitValue);
362 // Check for infinite loop, either:
363 // while (i >= Exit) or until (i < Exit)
364 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
365 if (++Range == 0)
366 return std::nullopt; // Range overflows.
367 }
368
369 unsigned Leftover = Range % uint32_t(-IncrValue);
370
371 // If this is an equality comparison, we require that the strided value
372 // exactly land on the exit value, otherwise the IV condition will wrap
373 // around and do things the fp IV wouldn't.
374 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
375 Leftover != 0)
376 return std::nullopt;
377
378 // If the stride would wrap around the i32 before exiting, we can't
379 // transform the IV.
380 if (Leftover != 0 && int32_t(ExitValue + IncrValue) > ExitValue)
381 return std::nullopt;
382 }
383
384 return IntegerIV{InitValue, IncrValue, ExitValue, NewPred};
385}
386
387/// Rewrite the floating-point IV as an integer IV.
389 const FloatingPointIV &FPIV,
390 const IntegerIV &IIV,
391 const TargetLibraryInfo *TLI,
392 std::unique_ptr<MemorySSAUpdater> &MSSAU) {
393 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
394 unsigned BackEdge = IncomingEdge ^ 1;
395
396 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
397 auto *Incr = cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
398 auto *BI = cast<CondBrInst>(FPIV.Compare->user_back());
399
400 LLVM_DEBUG(dbgs() << "INDVARS: Rewriting floating-point IV to integer IV:\n"
401 << " Init: " << IIV.InitValue << "\n"
402 << " Incr: " << IIV.IncrValue << "\n"
403 << " Exit: " << IIV.ExitValue << "\n"
404 << " Pred: " << CmpInst::getPredicateName(IIV.NewPred)
405 << "\n"
406 << " Original PN: " << *PN << "\n");
407
408 // Insert new integer induction variable.
409 PHINode *NewPHI =
410 PHINode::Create(Int32Ty, 2, PN->getName() + ".int", PN->getIterator());
411 NewPHI->addIncoming(ConstantInt::getSigned(Int32Ty, IIV.InitValue),
412 PN->getIncomingBlock(IncomingEdge));
413 NewPHI->setDebugLoc(PN->getDebugLoc());
414
415 Instruction *NewAdd = BinaryOperator::CreateAdd(
416 NewPHI, ConstantInt::getSigned(Int32Ty, IIV.IncrValue),
417 Incr->getName() + ".int", Incr->getIterator());
418 NewAdd->setDebugLoc(Incr->getDebugLoc());
419 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
420
421 ICmpInst *NewCompare = new ICmpInst(
422 BI->getIterator(), IIV.NewPred, NewAdd,
423 ConstantInt::getSigned(Int32Ty, IIV.ExitValue), FPIV.Compare->getName());
424 NewCompare->setDebugLoc(FPIV.Compare->getDebugLoc());
425
426 // In the following deletions, PN may become dead and may be deleted.
427 // Use a WeakTrackingVH to observe whether this happens.
428 WeakTrackingVH WeakPH = PN;
429
430 // Delete the old floating point exit comparison. The branch starts using the
431 // new comparison.
432 NewCompare->takeName(FPIV.Compare);
433 FPIV.Compare->replaceAllUsesWith(NewCompare);
435
436 // Delete the old floating point increment.
437 Incr->replaceAllUsesWith(PoisonValue::get(Incr->getType()));
438 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI, MSSAU.get());
439
440 // If the FP induction variable still has uses, this is because something else
441 // in the loop uses its value. In order to canonicalize the induction
442 // variable, we chose to eliminate the IV and rewrite it in terms of an
443 // int->fp cast.
444 //
445 // We give preference to sitofp over uitofp because it is faster on most
446 // platforms.
447 if (WeakPH) {
448 Instruction *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
449 PN->getParent()->getFirstInsertionPt());
450 Conv->setDebugLoc(PN->getDebugLoc());
451 PN->replaceAllUsesWith(Conv);
452 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI, MSSAU.get());
453 }
454}
455
456/// If the loop has a floating induction variable, then insert corresponding
457/// integer induction variable if possible. For example, the following:
458/// for(double i = 0; i < 10000; ++i)
459/// bar(i)
460/// is converted into
461/// for(int i = 0; i < 10000; ++i)
462/// bar((double)i);
463bool IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
464 // See if the PN matches a floating-point IV pattern.
465 auto FPIV = maybeFloatingPointRecurrence(L, PN);
466 if (!FPIV)
467 return false;
468
469 // Can we safely convert the floating-point values to integer ones?
470 auto IIV = tryConvertToIntegerIV(*FPIV);
471 if (!IIV)
472 return false;
473
474 // Perform the rewriting.
475 canonicalizeToIntegerIV(L, PN, *FPIV, *IIV, TLI, MSSAU);
476 return true;
477}
478
479bool IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
480 // First step. Check to see if there are any floating-point recurrences.
481 // If there are, change them into integer recurrences, permitting analysis by
482 // the SCEV routines.
483 BasicBlock *Header = L->getHeader();
484
486
487 bool Changed = false;
488 for (WeakTrackingVH &PHI : PHIs)
489 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHI))
490 Changed |= handleFloatingPointIV(L, PN);
491
492 // If the loop previously had floating-point IV, ScalarEvolution
493 // may not have been able to compute a trip count. Now that we've done some
494 // re-writing, the trip count may be computable.
495 if (Changed)
496 SE->forgetLoop(L);
497 return Changed;
498}
499
500//===---------------------------------------------------------------------===//
501// rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
502// they will exit at the first iteration.
503//===---------------------------------------------------------------------===//
504
505/// Check to see if this loop has loop invariant conditions which lead to loop
506/// exits. If so, we know that if the exit path is taken, it is at the first
507/// loop iteration. This lets us predict exit values of PHI nodes that live in
508/// loop header.
509bool IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
510 // Verify the input to the pass is already in LCSSA form.
511 assert(L->isLCSSAForm(*DT));
512
513 SmallVector<BasicBlock *, 8> ExitBlocks;
514 L->getUniqueExitBlocks(ExitBlocks);
515
516 bool MadeAnyChanges = false;
517 for (auto *ExitBB : ExitBlocks) {
518 // If there are no more PHI nodes in this exit block, then no more
519 // values defined inside the loop are used on this path.
520 for (PHINode &PN : ExitBB->phis()) {
521 for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
522 IncomingValIdx != E; ++IncomingValIdx) {
523 auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
524
525 // Can we prove that the exit must run on the first iteration if it
526 // runs at all? (i.e. early exits are fine for our purposes, but
527 // traces which lead to this exit being taken on the 2nd iteration
528 // aren't.) Note that this is about whether the exit branch is
529 // executed, not about whether it is taken.
530 if (!L->getLoopLatch() ||
531 !DT->dominates(IncomingBB, L->getLoopLatch()))
532 continue;
533
534 // Get condition that leads to the exit path.
535 auto *TermInst = IncomingBB->getTerminator();
536
537 Value *Cond = nullptr;
538 if (auto *BI = dyn_cast<CondBrInst>(TermInst)) {
539 // Must be a conditional branch, otherwise the block
540 // should not be in the loop.
541 Cond = BI->getCondition();
542 } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
543 Cond = SI->getCondition();
544 else
545 continue;
546
547 if (!L->isLoopInvariant(Cond))
548 continue;
549
550 auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
551
552 // Only deal with PHIs in the loop header.
553 if (!ExitVal || ExitVal->getParent() != L->getHeader())
554 continue;
555
556 // If ExitVal is a PHI on the loop header, then we know its
557 // value along this exit because the exit can only be taken
558 // on the first iteration.
559 auto *LoopPreheader = L->getLoopPreheader();
560 assert(LoopPreheader && "Invalid loop");
561 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
562 if (PreheaderIdx != -1) {
563 assert(ExitVal->getParent() == L->getHeader() &&
564 "ExitVal must be in loop header");
565 MadeAnyChanges = true;
566 PN.setIncomingValue(IncomingValIdx,
567 ExitVal->getIncomingValue(PreheaderIdx));
568 SE->forgetValue(&PN);
569 }
570 }
571 }
572 }
573 return MadeAnyChanges;
574}
575
576//===----------------------------------------------------------------------===//
577// IV Widening - Extend the width of an IV to cover its widest uses.
578//===----------------------------------------------------------------------===//
579
580/// Update information about the induction variable that is extended by this
581/// sign or zero extend operation. This is used to determine the final width of
582/// the IV before actually widening it.
583static void visitIVCast(CastInst *Cast, WideIVInfo &WI,
584 ScalarEvolution *SE,
585 const TargetTransformInfo *TTI) {
586 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
587 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
588 return;
589
590 Type *Ty = Cast->getType();
591 uint64_t Width = SE->getTypeSizeInBits(Ty);
592 if (!Cast->getDataLayout().isLegalInteger(Width))
593 return;
594
595 // Check that `Cast` actually extends the induction variable (we rely on this
596 // later). This takes care of cases where `Cast` is extending a truncation of
597 // the narrow induction variable, and thus can end up being narrower than the
598 // "narrow" induction variable.
599 uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
600 if (NarrowIVWidth >= Width)
601 return;
602
603 // Cast is either an sext or zext up to this point.
604 // We should not widen an indvar if arithmetics on the wider indvar are more
605 // expensive than those on the narrower indvar. We check only the cost of ADD
606 // because at least an ADD is required to increment the induction variable. We
607 // could compute more comprehensively the cost of all instructions on the
608 // induction variable when necessary.
610 if (TTI && TTI->getArithmeticInstrCost(Instruction::Add, Ty, CostKind) >
611 TTI->getArithmeticInstrCost(Instruction::Add,
612 Cast->getOperand(0)->getType(),
613 CostKind)) {
614 return;
615 }
616
617 if (!WI.WidestNativeType ||
618 Width > SE->getTypeSizeInBits(WI.WidestNativeType)) {
620 WI.IsSigned = IsSigned;
621 return;
622 }
623
624 // We extend the IV to satisfy the sign of its user(s), or 'signed'
625 // if there are multiple users with both sign- and zero extensions,
626 // in order not to introduce nondeterministic behaviour based on the
627 // unspecified order of a PHI nodes' users-iterator.
628 WI.IsSigned |= IsSigned;
629}
630
631//===----------------------------------------------------------------------===//
632// Live IV Reduction - Minimize IVs live across the loop.
633//===----------------------------------------------------------------------===//
634
635//===----------------------------------------------------------------------===//
636// Simplification of IV users based on SCEV evaluation.
637//===----------------------------------------------------------------------===//
638
639namespace {
640
641class IndVarSimplifyVisitor : public IVVisitor {
642 ScalarEvolution *SE;
643 const TargetTransformInfo *TTI;
644 PHINode *IVPhi;
645
646public:
647 WideIVInfo WI;
648
649 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
650 const TargetTransformInfo *TTI,
651 const DominatorTree *DTree)
652 : SE(SCEV), TTI(TTI), IVPhi(IV) {
653 DT = DTree;
654 WI.NarrowIV = IVPhi;
655 }
656
657 // Implement the interface used by simplifyUsersOfIV.
658 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
659};
660
661} // end anonymous namespace
662
663/// Iteratively perform simplification on a worklist of IV users. Each
664/// successive simplification may push more users which may themselves be
665/// candidates for simplification.
666///
667/// Sign/Zero extend elimination is interleaved with IV simplification.
668bool IndVarSimplify::simplifyAndExtend(Loop *L,
669 SCEVExpander &Rewriter,
670 LoopInfo *LI) {
672
673 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
674 L->getBlocks()[0]->getModule(), Intrinsic::experimental_guard);
675 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
676
678 llvm::make_pointer_range(L->getHeader()->phis()));
679
680 // Each round of simplification iterates through the SimplifyIVUsers worklist
681 // for all current phis, then determines whether any IVs can be
682 // widened. Widening adds new phis to LoopPhis, inducing another round of
683 // simplification on the wide IVs.
684 bool Changed = false;
685 while (!LoopPhis.empty()) {
686 // Evaluate as many IV expressions as possible before widening any IVs. This
687 // forces SCEV to set no-wrap flags before evaluating sign/zero
688 // extension. The first time SCEV attempts to normalize sign/zero extension,
689 // the result becomes final. So for the most predictable results, we delay
690 // evaluation of sign/zero extend evaluation until needed, and avoid running
691 // other SCEV based analysis prior to simplifyAndExtend.
692 do {
693 PHINode *CurrIV = LoopPhis.pop_back_val();
694
695 // Information about sign/zero extensions of CurrIV.
696 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
697
698 const auto &[C, U] = simplifyUsersOfIV(CurrIV, SE, DT, LI, TTI, DeadInsts,
699 Rewriter, &Visitor);
700
701 Changed |= C;
702 RunUnswitching |= U;
703 if (Visitor.WI.WidestNativeType) {
704 WideIVs.push_back(Visitor.WI);
705 }
706 } while(!LoopPhis.empty());
707
708 // Continue if we disallowed widening.
709 if (!WidenIndVars)
710 continue;
711
712 for (; !WideIVs.empty(); WideIVs.pop_back()) {
713 unsigned ElimExt;
714 unsigned Widened;
715 if (PHINode *WidePhi = createWideIV(
716 WideIVs.back(), LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
717 HasGuards, Opts.indvars_post_increment_ranges)) {
718 NumElimExt += ElimExt;
719 NumWidened += Widened;
720 Changed = true;
721 LoopPhis.push_back(WidePhi);
722 }
723 }
724 }
725 return Changed;
726}
727
728//===----------------------------------------------------------------------===//
729// linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
730//===----------------------------------------------------------------------===//
731
732/// Given an Value which is hoped to be part of an add recurance in the given
733/// loop, return the associated Phi node if so. Otherwise, return null. Note
734/// that this is less general than SCEVs AddRec checking.
737 if (!IncI)
738 return nullptr;
739
740 switch (IncI->getOpcode()) {
741 case Instruction::Add:
742 case Instruction::Sub:
743 break;
744 case Instruction::GetElementPtr:
745 // An IV counter must preserve its type.
746 if (IncI->getNumOperands() == 2)
747 break;
748 [[fallthrough]];
749 default:
750 return nullptr;
751 }
752
753 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
754 if (Phi && Phi->getParent() == L->getHeader()) {
755 if (L->isLoopInvariant(IncI->getOperand(1)))
756 return Phi;
757 return nullptr;
758 }
759 if (IncI->getOpcode() == Instruction::GetElementPtr)
760 return nullptr;
761
762 // Allow add/sub to be commuted.
763 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
764 if (Phi && Phi->getParent() == L->getHeader()) {
765 if (L->isLoopInvariant(IncI->getOperand(0)))
766 return Phi;
767 }
768 return nullptr;
769}
770
771/// Whether the current loop exit test is based on this value. Currently this
772/// is limited to a direct use in the loop condition.
773static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB) {
774 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
776 // TODO: Allow non-icmp loop test.
777 if (!ICmp)
778 return false;
779
780 // TODO: Allow indirect use.
781 return ICmp->getOperand(0) == V || ICmp->getOperand(1) == V;
782}
783
784/// linearFunctionTestReplace policy. Return true unless we can show that the
785/// current exit test is already sufficiently canonical.
786static bool needsLFTR(Loop *L, BasicBlock *ExitingBB) {
787 assert(L->getLoopLatch() && "Must be in simplified form");
788
789 // Avoid converting a constant or loop invariant test back to a runtime
790 // test. This is critical for when SCEV's cached ExitCount is less precise
791 // than the current IR (such as after we've proven a particular exit is
792 // actually dead and thus the BE count never reaches our ExitCount.)
793 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
794 if (L->isLoopInvariant(BI->getCondition()))
795 return false;
796
797 // Do LFTR to simplify the exit condition to an ICMP.
799 if (!Cond)
800 return true;
801
802 // Do LFTR to simplify the exit ICMP to EQ/NE
803 ICmpInst::Predicate Pred = Cond->getPredicate();
804 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
805 return true;
806
807 // Look for a loop invariant RHS
808 Value *LHS = Cond->getOperand(0);
809 Value *RHS = Cond->getOperand(1);
810 if (!L->isLoopInvariant(RHS)) {
811 if (!L->isLoopInvariant(LHS))
812 return true;
813 std::swap(LHS, RHS);
814 }
815 // Look for a simple IV counter LHS
817 if (!Phi)
818 Phi = getLoopPhiForCounter(LHS, L);
819
820 if (!Phi)
821 return true;
822
823 // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
824 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
825 if (Idx < 0)
826 return true;
827
828 // Do LFTR if the exit condition's IV is *not* a simple counter.
829 Value *IncV = Phi->getIncomingValue(Idx);
830 return Phi != getLoopPhiForCounter(IncV, L);
831}
832
833/// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
834/// down to checking that all operands are constant and listing instructions
835/// that may hide undef.
837 unsigned Depth) {
838 if (isa<Constant>(V))
839 return !isa<UndefValue>(V);
840
841 if (Depth >= 6)
842 return false;
843
844 // Conservatively handle non-constant non-instructions. For example, Arguments
845 // may be undef.
847 if (!I)
848 return false;
849
850 // Load and return values may be undef.
851 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
852 return false;
853
854 // Optimistically handle other instructions.
855 for (Value *Op : I->operands()) {
856 if (!Visited.insert(Op).second)
857 continue;
858 if (!hasConcreteDefImpl(Op, Visited, Depth+1))
859 return false;
860 }
861 return true;
862}
863
864/// Return true if the given value is concrete. We must prove that undef can
865/// never reach it.
866///
867/// TODO: If we decide that this is a good approach to checking for undef, we
868/// may factor it into a common location.
869static bool hasConcreteDef(Value *V) {
871 Visited.insert(V);
872 return hasConcreteDefImpl(V, Visited, 0);
873}
874
875/// Return true if the given phi is a "counter" in L. A counter is an
876/// add recurance (of integer or pointer type) with an arbitrary start, and a
877/// step of 1. Note that L must have exactly one latch.
878static bool isLoopCounter(PHINode* Phi, Loop *L,
879 ScalarEvolution *SE) {
880 assert(Phi->getParent() == L->getHeader());
881 assert(L->getLoopLatch());
882
883 if (!SE->isSCEVable(Phi->getType()))
884 return false;
885
886 const SCEV *S = SE->getSCEV(Phi);
888 return false;
889
890 int LatchIdx = Phi->getBasicBlockIndex(L->getLoopLatch());
891 Value *IncV = Phi->getIncomingValue(LatchIdx);
892 return (getLoopPhiForCounter(IncV, L) == Phi &&
893 isa<SCEVAddRecExpr>(SE->getSCEV(IncV)));
894}
895
896/// Search the loop header for a loop counter (anadd rec w/step of one)
897/// suitable for use by LFTR. If multiple counters are available, select the
898/// "best" one based profitable heuristics.
899///
900/// BECount may be an i8* pointer type. The pointer difference is already
901/// valid count without scaling the address stride, so it remains a pointer
902/// expression as far as SCEV is concerned.
903static PHINode *FindLoopCounter(Loop *L, BasicBlock *ExitingBB,
904 const SCEV *BECount,
906 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
907
908 Value *Cond = cast<CondBrInst>(ExitingBB->getTerminator())->getCondition();
909
910 // Loop over all of the PHI nodes, looking for a simple counter.
911 PHINode *BestPhi = nullptr;
912 const SCEV *BestInit = nullptr;
913 BasicBlock *LatchBlock = L->getLoopLatch();
914 assert(LatchBlock && "Must be in simplified form");
915 const DataLayout &DL = L->getHeader()->getDataLayout();
916
917 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
918 PHINode *Phi = cast<PHINode>(I);
919 if (!isLoopCounter(Phi, L, SE))
920 continue;
921
922 const auto *AR = cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
923
924 // AR may be a pointer type, while BECount is an integer type.
925 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
926 // AR may not be a narrower type, or we may never exit.
927 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
928 if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
929 continue;
930
931 // Avoid reusing a potentially undef value to compute other values that may
932 // have originally had a concrete definition.
933 if (!hasConcreteDef(Phi)) {
934 // We explicitly allow unknown phis as long as they are already used by
935 // the loop exit test. This is legal since performing LFTR could not
936 // increase the number of undef users.
937 Value *IncPhi = Phi->getIncomingValueForBlock(LatchBlock);
938 if (!isLoopExitTestBasedOn(Phi, ExitingBB) &&
939 !isLoopExitTestBasedOn(IncPhi, ExitingBB))
940 continue;
941 }
942
943 // Avoid introducing undefined behavior due to poison which didn't exist in
944 // the original program. (Annoyingly, the rules for poison and undef
945 // propagation are distinct, so this does NOT cover the undef case above.)
946 // We have to ensure that we don't introduce UB by introducing a use on an
947 // iteration where said IV produces poison. Our strategy here differs for
948 // pointers and integer IVs. For integers, we strip and reinfer as needed,
949 // see code in linearFunctionTestReplace. For pointers, we restrict
950 // transforms as there is no good way to reinfer inbounds once lost.
951 if (!Phi->getType()->isIntegerTy() &&
952 !mustExecuteUBIfPoisonOnPathTo(Phi, ExitingBB->getTerminator(), DT))
953 continue;
954
955 const SCEV *Init = AR->getStart();
956
957 if (BestPhi && !isAlmostDeadIV(BestPhi, LatchBlock, Cond)) {
958 // Don't force a live loop counter if another IV can be used.
959 if (isAlmostDeadIV(Phi, LatchBlock, Cond))
960 continue;
961
962 // Prefer to count-from-zero. This is a more "canonical" counter form. It
963 // also prefers integer to pointer IVs.
964 if (BestInit->isZero() != Init->isZero()) {
965 if (BestInit->isZero())
966 continue;
967 }
968 // If two IVs both count from zero or both count from nonzero then the
969 // narrower is likely a dead phi that has been widened. Use the wider phi
970 // to allow the other to be eliminated.
971 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
972 continue;
973 }
974 BestPhi = Phi;
975 BestInit = Init;
976 }
977 return BestPhi;
978}
979
980/// Insert an IR expression which computes the value held by the IV IndVar
981/// (which must be an loop counter w/unit stride) after the backedge of loop L
982/// is taken ExitCount times.
983static Value *genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB,
984 const SCEV *ExitCount, bool UsePostInc, Loop *L,
985 SCEVExpander &Rewriter, ScalarEvolution *SE) {
986 assert(isLoopCounter(IndVar, L, SE));
987 assert(ExitCount->getType()->isIntegerTy() && "exit count must be integer");
988 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
989 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
990
991 // For integer IVs, truncate the IV before computing the limit unless we
992 // know apriori that the limit must be a constant when evaluated in the
993 // bitwidth of the IV. We prefer (potentially) keeping a truncate of the
994 // IV in the loop over a (potentially) expensive expansion of the widened
995 // exit count add(zext(add)) expression.
996 if (IndVar->getType()->isIntegerTy() &&
997 SE->getTypeSizeInBits(AR->getType()) >
998 SE->getTypeSizeInBits(ExitCount->getType())) {
999 const SCEV *IVInit = AR->getStart();
1000 if (!isa<SCEVConstant>(IVInit) || !isa<SCEVConstant>(ExitCount)) {
1001 const SCEV *TruncExpr = SE->getTruncateExpr(AR, ExitCount->getType());
1002
1003 // The following bailout is necessary due to the interaction with
1004 // the depth limit in SCEV analysis.
1005 if (!isa<SCEVAddRecExpr>(TruncExpr))
1006 return nullptr;
1007 AR = cast<SCEVAddRecExpr>(TruncExpr);
1008 }
1009 }
1010
1011 const SCEVAddRecExpr *ARBase = UsePostInc ? AR->getPostIncExpr(*SE) : AR;
1012 const SCEV *IVLimit = ARBase->evaluateAtIteration(ExitCount, *SE);
1013 assert(SE->isLoopInvariant(IVLimit, L) &&
1014 "Computed iteration count is not loop invariant!");
1015 return Rewriter.expandCodeFor(IVLimit, ARBase->getType(),
1016 ExitingBB->getTerminator());
1017}
1018
1019/// This method rewrites the exit condition of the loop to be a canonical !=
1020/// comparison against the incremented loop induction variable. This pass is
1021/// able to rewrite the exit tests of any loop where the SCEV analysis can
1022/// determine a loop-invariant trip count of the loop, which is actually a much
1023/// broader range than just linear tests.
1024bool IndVarSimplify::
1025linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
1026 const SCEV *ExitCount,
1027 PHINode *IndVar, SCEVExpander &Rewriter) {
1028 assert(L->getLoopLatch() && "Loop no longer in simplified form?");
1029 assert(isLoopCounter(IndVar, L, SE));
1030 Instruction * const IncVar =
1031 cast<Instruction>(IndVar->getIncomingValueForBlock(L->getLoopLatch()));
1032
1033 // Initialize CmpIndVar to the preincremented IV.
1034 Value *CmpIndVar = IndVar;
1035 bool UsePostInc = false;
1036
1037 // If the exiting block is the same as the backedge block, we prefer to
1038 // compare against the post-incremented value, otherwise we must compare
1039 // against the preincremented value.
1040 if (ExitingBB == L->getLoopLatch()) {
1041 // For pointer IVs, we chose to not strip inbounds which requires us not
1042 // to add a potentially UB introducing use. We need to either a) show
1043 // the loop test we're modifying is already in post-inc form, or b) show
1044 // that adding a use must not introduce UB.
1045 bool SafeToPostInc =
1046 IndVar->getType()->isIntegerTy() ||
1047 isLoopExitTestBasedOn(IncVar, ExitingBB) ||
1048 mustExecuteUBIfPoisonOnPathTo(IncVar, ExitingBB->getTerminator(), DT);
1049 if (SafeToPostInc) {
1050 UsePostInc = true;
1051 CmpIndVar = IncVar;
1052 }
1053 }
1054
1055 Value *ExitCnt =
1056 genLoopLimit(IndVar, ExitingBB, ExitCount, UsePostInc, L, Rewriter, SE);
1057 if (!ExitCnt)
1058 return false;
1059
1060 assert(ExitCnt->getType()->isPointerTy() ==
1061 IndVar->getType()->isPointerTy() &&
1062 "genLoopLimit missed a cast");
1063
1064 // It may be necessary to drop nowrap flags on the incrementing instruction
1065 // if either LFTR moves from a pre-inc check to a post-inc check (in which
1066 // case the increment might have previously been poison on the last iteration
1067 // only) or if LFTR switches to a different IV that was previously dynamically
1068 // dead (and as such may be arbitrarily poison). We remove any nowrap flags
1069 // that SCEV didn't infer for the post-inc addrec (even if we use a pre-inc
1070 // check), because the pre-inc addrec flags may be adopted from the original
1071 // instruction, while SCEV has to explicitly prove the post-inc nowrap flags.
1072 // TODO: This handling is inaccurate for one case: If we switch to a
1073 // dynamically dead IV that wraps on the first loop iteration only, which is
1074 // not covered by the post-inc addrec. (If the new IV was not dynamically
1075 // dead, it could not be poison on the first iteration in the first place.)
1076 if (auto *BO = dyn_cast<BinaryOperator>(IncVar)) {
1077 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));
1078 if (BO->hasNoUnsignedWrap())
1079 BO->setHasNoUnsignedWrap(AR->hasNoUnsignedWrap());
1080 if (BO->hasNoSignedWrap())
1081 BO->setHasNoSignedWrap(AR->hasNoSignedWrap());
1082 }
1083
1084 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1085 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1086 ICmpInst::Predicate P;
1087 if (L->contains(BI->getSuccessor(0)))
1088 P = ICmpInst::ICMP_NE;
1089 else
1090 P = ICmpInst::ICMP_EQ;
1091
1092 IRBuilder<> Builder(BI);
1093
1094 // The new loop exit condition should reuse the debug location of the
1095 // original loop exit condition.
1096 if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
1097 Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
1098
1099 // For integer IVs, if we evaluated the limit in the narrower bitwidth to
1100 // avoid the expensive expansion of the limit expression in the wider type,
1101 // emit a truncate to narrow the IV to the ExitCount type. This is safe
1102 // since we know (from the exit count bitwidth), that we can't self-wrap in
1103 // the narrower type.
1104 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
1105 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
1106 if (CmpIndVarSize > ExitCntSize) {
1107 assert(!CmpIndVar->getType()->isPointerTy() &&
1108 !ExitCnt->getType()->isPointerTy());
1109
1110 // Before resorting to actually inserting the truncate, use the same
1111 // reasoning as from SimplifyIndvar::eliminateTrunc to see if we can extend
1112 // the other side of the comparison instead. We still evaluate the limit
1113 // in the narrower bitwidth, we just prefer a zext/sext outside the loop to
1114 // a truncate within in.
1115 bool Extended = false;
1116 const SCEV *IV = SE->getSCEV(CmpIndVar);
1117 const SCEV *TruncatedIV = SE->getTruncateExpr(IV, ExitCnt->getType());
1118 const SCEV *ZExtTrunc =
1119 SE->getZeroExtendExpr(TruncatedIV, CmpIndVar->getType());
1120
1121 if (ZExtTrunc == IV) {
1122 Extended = true;
1123 ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
1124 "wide.trip.count");
1125 } else {
1126 const SCEV *SExtTrunc =
1127 SE->getSignExtendExpr(TruncatedIV, CmpIndVar->getType());
1128 if (SExtTrunc == IV) {
1129 Extended = true;
1130 ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
1131 "wide.trip.count");
1132 }
1133 }
1134
1135 if (Extended) {
1136 bool Discard;
1137 L->makeLoopInvariant(ExitCnt, Discard);
1138 } else
1139 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
1140 "lftr.wideiv");
1141 }
1142 LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1143 << " LHS:" << *CmpIndVar << '\n'
1144 << " op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")
1145 << "\n"
1146 << " RHS:\t" << *ExitCnt << "\n"
1147 << "ExitCount:\t" << *ExitCount << "\n"
1148 << " was: " << *BI->getCondition() << "\n");
1149
1150 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
1151 Value *OrigCond = BI->getCondition();
1152 // It's tempting to use replaceAllUsesWith here to fully replace the old
1153 // comparison, but that's not immediately safe, since users of the old
1154 // comparison may not be dominated by the new comparison. Instead, just
1155 // update the branch to use the new comparison; in the common case this
1156 // will make old comparison dead.
1157 BI->setCondition(Cond);
1158 DeadInsts.emplace_back(OrigCond);
1159
1160 ++NumLFTR;
1161 return true;
1162}
1163
1164//===----------------------------------------------------------------------===//
1165// sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1166//===----------------------------------------------------------------------===//
1167
1168/// If there's a single exit block, sink any loop-invariant values that
1169/// were defined in the preheader but not used inside the loop into the
1170/// exit block to reduce register pressure in the loop.
1171bool IndVarSimplify::sinkUnusedInvariants(Loop *L) {
1172 BasicBlock *ExitBlock = L->getExitBlock();
1173 if (!ExitBlock) return false;
1174
1175 BasicBlock *Preheader = L->getLoopPreheader();
1176 if (!Preheader) return false;
1177
1178 bool MadeAnyChanges = false;
1179 SmallVector<Value *, 16> SunkInsts;
1180 for (Instruction &I : llvm::make_early_inc_range(llvm::reverse(*Preheader))) {
1181
1182 // Skip BB Terminator.
1183 if (Preheader->getTerminator() == &I)
1184 continue;
1185
1186 // New instructions were inserted at the end of the preheader.
1187 if (isa<PHINode>(I))
1188 break;
1189
1190 // Don't move instructions which might have side effects, since the side
1191 // effects need to complete before instructions inside the loop. Also don't
1192 // move instructions which might read memory, since the loop may modify
1193 // memory. Note that it's okay if the instruction might have undefined
1194 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1195 // block.
1196 if (I.mayHaveSideEffects() || I.mayReadFromMemory())
1197 continue;
1198
1199 // Skip eh pad instructions.
1200 if (I.isEHPad())
1201 continue;
1202
1203 // Don't sink alloca: we never want to sink static alloca's out of the
1204 // entry block, and correctly sinking dynamic alloca's requires
1205 // checks for stacksave/stackrestore intrinsics.
1206 // FIXME: Refactor this check somehow?
1207 if (isa<AllocaInst>(&I))
1208 continue;
1209
1210 // Determine if there is a use in or before the loop (direct or
1211 // otherwise).
1212 bool UsedInLoop = false;
1213 for (Use &U : I.uses()) {
1214 Instruction *User = cast<Instruction>(U.getUser());
1215 BasicBlock *UseBB = User->getParent();
1216 if (PHINode *P = dyn_cast<PHINode>(User)) {
1217 unsigned i =
1219 UseBB = P->getIncomingBlock(i);
1220 }
1221 if (UseBB == Preheader || L->contains(UseBB)) {
1222 UsedInLoop = true;
1223 break;
1224 }
1225 }
1226
1227 // If there is, the def must remain in the preheader.
1228 if (UsedInLoop)
1229 continue;
1230
1231 // Otherwise, sink it to the exit block.
1232 I.moveBefore(ExitBlock->getFirstInsertionPt());
1233 SunkInsts.push_back(&I);
1234 MadeAnyChanges = true;
1235 }
1236
1237 if (!SunkInsts.empty())
1238 SE->forgetValues(SunkInsts);
1239
1240 return MadeAnyChanges;
1241}
1242
1243static void replaceExitCond(CondBrInst *BI, Value *NewCond,
1245 auto *OldCond = BI->getCondition();
1246 LLVM_DEBUG(dbgs() << "Replacing condition of loop-exiting branch " << *BI
1247 << " with " << *NewCond << "\n");
1248 BI->setCondition(NewCond);
1249 if (OldCond->use_empty())
1250 DeadInsts.emplace_back(OldCond);
1251}
1252
1253static Constant *createFoldedExitCond(const Loop *L, BasicBlock *ExitingBB,
1254 bool IsTaken) {
1255 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1256 bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1257 auto *OldCond = BI->getCondition();
1258 return ConstantInt::get(OldCond->getType(),
1259 IsTaken ? ExitIfTrue : !ExitIfTrue);
1260}
1261
1262static void foldExit(const Loop *L, BasicBlock *ExitingBB, bool IsTaken,
1264 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1265 auto *NewCond = createFoldedExitCond(L, ExitingBB, IsTaken);
1266 replaceExitCond(BI, NewCond, DeadInsts);
1267}
1268
1270 LoopInfo *LI, Loop *L, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1271 ScalarEvolution &SE) {
1272 assert(L->isLoopSimplifyForm() && "Should only do it in simplify form!");
1273 auto *LoopPreheader = L->getLoopPreheader();
1274 auto *LoopHeader = L->getHeader();
1276 for (auto &PN : LoopHeader->phis()) {
1277 auto *PreheaderIncoming = PN.getIncomingValueForBlock(LoopPreheader);
1278 for (User *U : PN.users())
1279 Worklist.push_back(cast<Instruction>(U));
1280 SE.forgetValue(&PN);
1281 PN.replaceAllUsesWith(PreheaderIncoming);
1282 DeadInsts.emplace_back(&PN);
1283 }
1284
1285 // Replacing with the preheader value will often allow IV users to simplify
1286 // (especially if the preheader value is a constant).
1288 while (!Worklist.empty()) {
1289 auto *I = cast<Instruction>(Worklist.pop_back_val());
1290 if (!Visited.insert(I).second)
1291 continue;
1292
1293 // Don't simplify instructions outside the loop.
1294 if (!L->contains(I))
1295 continue;
1296
1297 Value *Res = simplifyInstruction(I, I->getDataLayout());
1298 if (Res && LI->replacementPreservesLCSSAForm(I, Res)) {
1299 for (User *U : I->users())
1300 Worklist.push_back(cast<Instruction>(U));
1301 I->replaceAllUsesWith(Res);
1302 DeadInsts.emplace_back(I);
1303 }
1304 }
1305}
1306
1307static Value *
1310 SCEVExpander &Rewriter) {
1311 ICmpInst::Predicate InvariantPred = LIP.Pred;
1312 BasicBlock *Preheader = L->getLoopPreheader();
1313 assert(Preheader && "Preheader doesn't exist");
1314 Rewriter.setInsertPoint(Preheader->getTerminator());
1315 auto *LHSV = Rewriter.expandCodeFor(LIP.LHS);
1316 auto *RHSV = Rewriter.expandCodeFor(LIP.RHS);
1317 bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1318 if (ExitIfTrue)
1319 InvariantPred = ICmpInst::getInversePredicate(InvariantPred);
1320 IRBuilder<> Builder(Preheader->getTerminator());
1321 CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1322 return Builder.CreateICmp(InvariantPred, LHSV, RHSV,
1323 BI->getCondition()->getName());
1324}
1325
1326static std::optional<Value *>
1327createReplacement(ICmpInst *ICmp, const Loop *L, BasicBlock *ExitingBB,
1328 const SCEV *MaxIter, bool Inverted, bool SkipLastIter,
1329 ScalarEvolution *SE, SCEVExpander &Rewriter) {
1330 CmpPredicate Pred = ICmp->getCmpPredicate();
1331 Value *LHS = ICmp->getOperand(0);
1332 Value *RHS = ICmp->getOperand(1);
1333
1334 // 'LHS pred RHS' should now mean that we stay in loop.
1335 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1336 if (Inverted)
1338
1339 const SCEV *LHSS = SE->getSCEVAtScope(LHS, L);
1340 const SCEV *RHSS = SE->getSCEVAtScope(RHS, L);
1341 // Can we prove it to be trivially true or false?
1342 if (auto EV = SE->evaluatePredicateAt(Pred, LHSS, RHSS, BI))
1343 return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ !*EV);
1344
1345 auto *ARTy = LHSS->getType();
1346 auto *MaxIterTy = MaxIter->getType();
1347 // If possible, adjust types.
1348 if (SE->getTypeSizeInBits(ARTy) > SE->getTypeSizeInBits(MaxIterTy))
1349 MaxIter = SE->getZeroExtendExpr(MaxIter, ARTy);
1350 else if (SE->getTypeSizeInBits(ARTy) < SE->getTypeSizeInBits(MaxIterTy)) {
1351 const SCEV *MinusOne = SE->getMinusOne(ARTy);
1352 const SCEV *MaxAllowedIter = SE->getZeroExtendExpr(MinusOne, MaxIterTy);
1353 if (SE->isKnownPredicateAt(ICmpInst::ICMP_ULE, MaxIter, MaxAllowedIter, BI))
1354 MaxIter = SE->getTruncateExpr(MaxIter, ARTy);
1355 }
1356
1357 if (SkipLastIter) {
1358 // Semantically skip last iter is "subtract 1, do not bother about unsigned
1359 // wrap". getLoopInvariantExitCondDuringFirstIterations knows how to deal
1360 // with umin in a smart way, but umin(a, b) - 1 will likely not simplify.
1361 // So we manually construct umin(a - 1, b - 1).
1362 SmallVector<SCEVUse, 4> Elements;
1363 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter)) {
1364 for (SCEVUse Op : UMin->operands())
1365 Elements.push_back(SE->getMinusSCEV(Op, SE->getOne(Op->getType())));
1366 MaxIter = SE->getUMinFromMismatchedTypes(Elements);
1367 } else
1368 MaxIter = SE->getMinusSCEV(MaxIter, SE->getOne(MaxIter->getType()));
1369 }
1370
1371 // Check if there is a loop-invariant predicate equivalent to our check.
1372 auto LIP = SE->getLoopInvariantExitCondDuringFirstIterations(Pred, LHSS, RHSS,
1373 L, BI, MaxIter);
1374 if (!LIP)
1375 return std::nullopt;
1376
1377 // Can we prove it to be trivially true?
1378 if (SE->isKnownPredicateAt(LIP->Pred, LIP->LHS, LIP->RHS, BI))
1379 return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ false);
1380 else
1381 return createInvariantCond(L, ExitingBB, *LIP, Rewriter);
1382}
1383
1385 const Loop *L, CondBrInst *BI, BasicBlock *ExitingBB, const SCEV *MaxIter,
1386 bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter,
1388 assert(
1389 (L->contains(BI->getSuccessor(0)) != L->contains(BI->getSuccessor(1))) &&
1390 "Not a loop exit!");
1391
1392 // For branch that stays in loop by TRUE condition, go through AND. For branch
1393 // that stays in loop by FALSE condition, go through OR. Both gives the
1394 // similar logic: "stay in loop iff all conditions are true(false)".
1395 bool Inverted = L->contains(BI->getSuccessor(1));
1396 SmallVector<ICmpInst *, 4> LeafConditions;
1397 SmallVector<Value *, 4> Worklist;
1399 Value *OldCond = BI->getCondition();
1400 Visited.insert(OldCond);
1401 Worklist.push_back(OldCond);
1402
1403 auto GoThrough = [&](Value *V) {
1404 Value *LHS = nullptr, *RHS = nullptr;
1405 if (Inverted) {
1406 if (!match(V, m_LogicalOr(m_Value(LHS), m_Value(RHS))))
1407 return false;
1408 } else {
1409 if (!match(V, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))
1410 return false;
1411 }
1412 if (Visited.insert(LHS).second)
1413 Worklist.push_back(LHS);
1414 if (Visited.insert(RHS).second)
1415 Worklist.push_back(RHS);
1416 return true;
1417 };
1418
1419 do {
1420 Value *Curr = Worklist.pop_back_val();
1421 // Go through AND/OR conditions. Collect leaf ICMPs. We only care about
1422 // those with one use, to avoid instruction duplication.
1423 if (Curr->hasOneUse())
1424 if (!GoThrough(Curr))
1425 if (auto *ICmp = dyn_cast<ICmpInst>(Curr))
1426 LeafConditions.push_back(ICmp);
1427 } while (!Worklist.empty());
1428
1429 // If the current basic block has the same exit count as the whole loop, and
1430 // it consists of multiple icmp's, try to collect all icmp's that give exact
1431 // same exit count. For all other icmp's, we could use one less iteration,
1432 // because their value on the last iteration doesn't really matter.
1433 SmallPtrSet<ICmpInst *, 4> ICmpsFailingOnLastIter;
1434 if (!SkipLastIter && LeafConditions.size() > 1 &&
1435 SE->getExitCount(L, ExitingBB,
1437 MaxIter)
1438 for (auto *ICmp : LeafConditions) {
1439 auto EL = SE->computeExitLimitFromCond(L, ICmp, Inverted,
1440 /*ControlsExit*/ false);
1441 const SCEV *ExitMax = EL.SymbolicMaxNotTaken;
1442 if (isa<SCEVCouldNotCompute>(ExitMax))
1443 continue;
1444 // They could be of different types (specifically this happens after
1445 // IV widening).
1446 auto *WiderType =
1447 SE->getWiderType(ExitMax->getType(), MaxIter->getType());
1448 const SCEV *WideExitMax = SE->getNoopOrZeroExtend(ExitMax, WiderType);
1449 const SCEV *WideMaxIter = SE->getNoopOrZeroExtend(MaxIter, WiderType);
1450 if (WideExitMax == WideMaxIter)
1451 ICmpsFailingOnLastIter.insert(ICmp);
1452 }
1453
1454 bool Changed = false;
1455 for (auto *OldCond : LeafConditions) {
1456 // Skip last iteration for this icmp under one of two conditions:
1457 // - We do it for all conditions;
1458 // - There is another ICmp that would fail on last iter, so this one doesn't
1459 // really matter.
1460 bool OptimisticSkipLastIter = SkipLastIter;
1461 if (!OptimisticSkipLastIter) {
1462 if (ICmpsFailingOnLastIter.size() > 1)
1463 OptimisticSkipLastIter = true;
1464 else if (ICmpsFailingOnLastIter.size() == 1)
1465 OptimisticSkipLastIter = !ICmpsFailingOnLastIter.count(OldCond);
1466 }
1467 if (auto Replaced =
1468 createReplacement(OldCond, L, ExitingBB, MaxIter, Inverted,
1469 OptimisticSkipLastIter, SE, Rewriter)) {
1470 Changed = true;
1471 auto *NewCond = *Replaced;
1472 if (auto *NCI = dyn_cast<Instruction>(NewCond)) {
1473 NCI->setName(OldCond->getName() + ".first_iter");
1474 }
1475 LLVM_DEBUG(dbgs() << "Unknown exit count: Replacing " << *OldCond
1476 << " with " << *NewCond << "\n");
1477 assert(OldCond->hasOneUse() && "Must be!");
1478 OldCond->replaceAllUsesWith(NewCond);
1479 DeadInsts.push_back(OldCond);
1480 // Make sure we no longer consider this condition as failing on last
1481 // iteration.
1482 ICmpsFailingOnLastIter.erase(OldCond);
1483 }
1484 }
1485 return Changed;
1486}
1487
1488bool IndVarSimplify::canonicalizeExitCondition(Loop *L) {
1489 // Note: This is duplicating a particular part on SimplifyIndVars reasoning.
1490 // We need to duplicate it because given icmp zext(small-iv), C, IVUsers
1491 // never reaches the icmp since the zext doesn't fold to an AddRec unless
1492 // it already has flags. The alternative to this would be to extending the
1493 // set of "interesting" IV users to include the icmp, but doing that
1494 // regresses results in practice by querying SCEVs before trip counts which
1495 // rely on them which results in SCEV caching sub-optimal answers. The
1496 // concern about caching sub-optimal results is why we only query SCEVs of
1497 // the loop invariant RHS here.
1498 SmallVector<BasicBlock*, 16> ExitingBlocks;
1499 L->getExitingBlocks(ExitingBlocks);
1500 bool Changed = false;
1501 for (auto *ExitingBB : ExitingBlocks) {
1502 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1503 if (!BI)
1504 continue;
1505
1506 auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());
1507 if (!ICmp || !ICmp->hasOneUse())
1508 continue;
1509
1510 auto *LHS = ICmp->getOperand(0);
1511 auto *RHS = ICmp->getOperand(1);
1512 // For the range reasoning, avoid computing SCEVs in the loop to avoid
1513 // poisoning cache with sub-optimal results. For the must-execute case,
1514 // this is a neccessary precondition for correctness.
1515 if (!L->isLoopInvariant(RHS)) {
1516 if (!L->isLoopInvariant(LHS))
1517 continue;
1518 // Same logic applies for the inverse case
1519 std::swap(LHS, RHS);
1520 }
1521
1522 // Match (icmp signed-cond zext, RHS)
1523 Value *LHSOp = nullptr;
1524 if (!match(LHS, m_ZExt(m_Value(LHSOp))) || !ICmp->isSigned())
1525 continue;
1526
1527 const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());
1528 const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());
1529 auto FullCR = ConstantRange::getFull(InnerBitWidth);
1530 FullCR = FullCR.zeroExtend(OuterBitWidth);
1531 auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));
1532 if (FullCR.contains(RHSCR)) {
1533 // We have now matched icmp signed-cond zext(X), zext(Y'), and can thus
1534 // replace the signed condition with the unsigned version.
1535 ICmp->setPredicate(ICmp->getUnsignedPredicate());
1536 Changed = true;
1537 // Note: No SCEV invalidation needed. We've changed the predicate, but
1538 // have not changed exit counts, or the values produced by the compare.
1539 continue;
1540 }
1541 }
1542
1543 // Now that we've canonicalized the condition to match the extend,
1544 // see if we can rotate the extend out of the loop.
1545 for (auto *ExitingBB : ExitingBlocks) {
1546 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1547 if (!BI)
1548 continue;
1549
1550 auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());
1551 if (!ICmp || !ICmp->hasOneUse() || !ICmp->isUnsigned())
1552 continue;
1553
1554 bool Swapped = false;
1555 auto *LHS = ICmp->getOperand(0);
1556 auto *RHS = ICmp->getOperand(1);
1557 if (L->isLoopInvariant(LHS) == L->isLoopInvariant(RHS))
1558 // Nothing to rotate
1559 continue;
1560 if (L->isLoopInvariant(LHS)) {
1561 // Same logic applies for the inverse case until we actually pick
1562 // which operand of the compare to update.
1563 Swapped = true;
1564 std::swap(LHS, RHS);
1565 }
1566 assert(!L->isLoopInvariant(LHS) && L->isLoopInvariant(RHS));
1567
1568 // Match (icmp unsigned-cond zext, RHS)
1569 // TODO: Extend to handle corresponding sext/signed-cmp case
1570 // TODO: Extend to other invertible functions
1571 Value *LHSOp = nullptr;
1572 if (!match(LHS, m_ZExt(m_Value(LHSOp))))
1573 continue;
1574
1575 // In general, we only rotate if we can do so without increasing the number
1576 // of instructions. The exception is when we have an zext(add-rec). The
1577 // reason for allowing this exception is that we know we need to get rid
1578 // of the zext for SCEV to be able to compute a trip count for said loops;
1579 // we consider the new trip count valuable enough to increase instruction
1580 // count by one.
1581 if (!LHS->hasOneUse() && !isa<SCEVAddRecExpr>(SE->getSCEV(LHSOp)))
1582 continue;
1583
1584 // Given a icmp unsigned-cond zext(Op) where zext(trunc(RHS)) == RHS
1585 // replace with an icmp of the form icmp unsigned-cond Op, trunc(RHS)
1586 // when zext is loop varying and RHS is loop invariant. This converts
1587 // loop varying work to loop-invariant work.
1588 auto doRotateTransform = [&]() {
1589 assert(ICmp->isUnsigned() && "must have proven unsigned already");
1590 auto *NewRHS = CastInst::Create(
1591 Instruction::Trunc, RHS, LHSOp->getType(), "",
1592 L->getLoopPreheader()->getTerminator()->getIterator());
1593 // NewRHS is an operation that has been hoisted out of the loop, and
1594 // therefore should have a dropped location.
1595 NewRHS->setDebugLoc(DebugLoc::getDropped());
1596 ICmp->setOperand(Swapped ? 1 : 0, LHSOp);
1597 ICmp->setOperand(Swapped ? 0 : 1, NewRHS);
1598 // Samesign flag cannot be preserved after narrowing the compare.
1599 ICmp->setSameSign(false);
1600 if (LHS->use_empty())
1601 DeadInsts.push_back(LHS);
1602 };
1603
1604 const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());
1605 const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());
1606 auto FullCR = ConstantRange::getFull(InnerBitWidth);
1607 FullCR = FullCR.zeroExtend(OuterBitWidth);
1608 auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));
1609 if (FullCR.contains(RHSCR)) {
1610 doRotateTransform();
1611 Changed = true;
1612 // Note, we are leaving SCEV in an unfortunately imprecise case here
1613 // as rotation tends to reveal information about trip counts not
1614 // previously visible.
1615 continue;
1616 }
1617 }
1618
1619 return Changed;
1620}
1621
1622bool IndVarSimplify::optimizeLoopExits(Loop *L, SCEVExpander &Rewriter) {
1623 SmallVector<BasicBlock*, 16> ExitingBlocks;
1624 L->getExitingBlocks(ExitingBlocks);
1625
1626 // Remove all exits which aren't both rewriteable and execute on every
1627 // iteration.
1628 llvm::erase_if(ExitingBlocks, [&](BasicBlock *ExitingBB) {
1629 // If our exitting block exits multiple loops, we can only rewrite the
1630 // innermost one. Otherwise, we're changing how many times the innermost
1631 // loop runs before it exits.
1632 if (LI->getLoopFor(ExitingBB) != L)
1633 return true;
1634
1635 // Can't rewrite non-branch yet.
1636 CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1637 if (!BI)
1638 return true;
1639
1640 // Likewise, the loop latch must be dominated by the exiting BB.
1641 if (!DT->dominates(ExitingBB, L->getLoopLatch()))
1642 return true;
1643
1644 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
1645 // If already constant, nothing to do. However, if this is an
1646 // unconditional exit, we can still replace header phis with their
1647 // preheader value.
1648 if (!L->contains(BI->getSuccessor(CI->isNullValue())))
1649 replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);
1650 return true;
1651 }
1652
1653 return false;
1654 });
1655
1656 if (ExitingBlocks.empty())
1657 return false;
1658
1659 // Get a symbolic upper bound on the loop backedge taken count.
1660 const SCEV *MaxBECount = SE->getSymbolicMaxBackedgeTakenCount(L);
1661 if (isa<SCEVCouldNotCompute>(MaxBECount))
1662 return false;
1663
1664 // Visit our exit blocks in order of dominance. We know from the fact that
1665 // all exits must dominate the latch, so there is a total dominance order
1666 // between them.
1667 llvm::sort(ExitingBlocks, [&](BasicBlock *A, BasicBlock *B) {
1668 // std::sort sorts in ascending order, so we want the inverse of
1669 // the normal dominance relation.
1670 if (A == B) return false;
1671 if (DT->properlyDominates(A, B))
1672 return true;
1673 else {
1674 assert(DT->properlyDominates(B, A) &&
1675 "expected total dominance order!");
1676 return false;
1677 }
1678 });
1679#ifdef ASSERT
1680 for (unsigned i = 1; i < ExitingBlocks.size(); i++) {
1681 assert(DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]));
1682 }
1683#endif
1684
1685 bool Changed = false;
1686 bool SkipLastIter = false;
1687 const SCEV *CurrMaxExit = SE->getCouldNotCompute();
1688 auto UpdateSkipLastIter = [&](const SCEV *MaxExitCount) {
1689 if (SkipLastIter || isa<SCEVCouldNotCompute>(MaxExitCount))
1690 return;
1691 if (isa<SCEVCouldNotCompute>(CurrMaxExit))
1692 CurrMaxExit = MaxExitCount;
1693 else
1694 CurrMaxExit = SE->getUMinFromMismatchedTypes(CurrMaxExit, MaxExitCount);
1695 // If the loop has more than 1 iteration, all further checks will be
1696 // executed 1 iteration less.
1697 if (CurrMaxExit == MaxBECount)
1698 SkipLastIter = true;
1699 };
1700 SmallPtrSet<const SCEV *, 8> DominatingExactExitCounts;
1701 for (BasicBlock *ExitingBB : ExitingBlocks) {
1702 const SCEV *ExactExitCount = SE->getExitCount(L, ExitingBB);
1703 const SCEV *MaxExitCount = SE->getExitCount(
1704 L, ExitingBB, ScalarEvolution::ExitCountKind::SymbolicMaximum);
1705 if (isa<SCEVCouldNotCompute>(ExactExitCount)) {
1706 // Okay, we do not know the exit count here. Can we at least prove that it
1707 // will remain the same within iteration space?
1708 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1709 auto OptimizeCond = [&](bool SkipLastIter) {
1710 return optimizeLoopExitWithUnknownExitCount(L, BI, ExitingBB,
1711 MaxBECount, SkipLastIter,
1712 SE, Rewriter, DeadInsts);
1713 };
1714
1715 // TODO: We might have proved that we can skip the last iteration for
1716 // this check. In this case, we only want to check the condition on the
1717 // pre-last iteration (MaxBECount - 1). However, there is a nasty
1718 // corner case:
1719 //
1720 // for (i = len; i != 0; i--) { ... check (i ult X) ... }
1721 //
1722 // If we could not prove that len != 0, then we also could not prove that
1723 // (len - 1) is not a UINT_MAX. If we simply query (len - 1), then
1724 // OptimizeCond will likely not prove anything for it, even if it could
1725 // prove the same fact for len.
1726 //
1727 // As a temporary solution, we query both last and pre-last iterations in
1728 // hope that we will be able to prove triviality for at least one of
1729 // them. We can stop querying MaxBECount for this case once SCEV
1730 // understands that (MaxBECount - 1) will not overflow here.
1731 if (OptimizeCond(false))
1732 Changed = true;
1733 else if (SkipLastIter && OptimizeCond(true))
1734 Changed = true;
1735 UpdateSkipLastIter(MaxExitCount);
1736 continue;
1737 }
1738
1739 UpdateSkipLastIter(ExactExitCount);
1740
1741 // If we know we'd exit on the first iteration, rewrite the exit to
1742 // reflect this. This does not imply the loop must exit through this
1743 // exit; there may be an earlier one taken on the first iteration.
1744 // We know that the backedge can't be taken, so we replace all
1745 // the header PHIs with values coming from the preheader.
1746 if (ExactExitCount->isZero()) {
1747 foldExit(L, ExitingBB, true, DeadInsts);
1748 replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);
1749 Changed = true;
1750 continue;
1751 }
1752
1753 assert(ExactExitCount->getType()->isIntegerTy() &&
1754 MaxBECount->getType()->isIntegerTy() &&
1755 "Exit counts must be integers");
1756
1757 Type *WiderType =
1758 SE->getWiderType(MaxBECount->getType(), ExactExitCount->getType());
1759 ExactExitCount = SE->getNoopOrZeroExtend(ExactExitCount, WiderType);
1760 MaxBECount = SE->getNoopOrZeroExtend(MaxBECount, WiderType);
1761 assert(MaxBECount->getType() == ExactExitCount->getType());
1762
1763 // Can we prove that some other exit must be taken strictly before this
1764 // one?
1765 if (SE->isLoopEntryGuardedByCond(L, CmpInst::ICMP_ULT, MaxBECount,
1766 ExactExitCount)) {
1767 foldExit(L, ExitingBB, false, DeadInsts);
1768 Changed = true;
1769 continue;
1770 }
1771
1772 // As we run, keep track of which exit counts we've encountered. If we
1773 // find a duplicate, we've found an exit which would have exited on the
1774 // exiting iteration, but (from the visit order) strictly follows another
1775 // which does the same and is thus dead.
1776 if (!DominatingExactExitCounts.insert(ExactExitCount).second) {
1777 foldExit(L, ExitingBB, false, DeadInsts);
1778 Changed = true;
1779 continue;
1780 }
1781
1782 // TODO: There might be another oppurtunity to leverage SCEV's reasoning
1783 // here. If we kept track of the min of dominanting exits so far, we could
1784 // discharge exits with EC >= MDEC. This is less powerful than the existing
1785 // transform (since later exits aren't considered), but potentially more
1786 // powerful for any case where SCEV can prove a >=u b, but neither a == b
1787 // or a >u b. Such a case is not currently known.
1788 }
1789 return Changed;
1790}
1791
1792static bool crashingBBWithoutEffect(const BasicBlock &BB) {
1793 return llvm::all_of(BB, [](const Instruction &I) {
1794 // TODO: for now this is overly restrictive, to make sure nothing in this
1795 // BB can depend on the loop body.
1796 // It's not enough to check for !I.mayHaveSideEffects(), because e.g. a
1797 // load does not have a side effect, but we could have
1798 // %a = load ptr, ptr %ptr
1799 // %b = load i32, ptr %a
1800 // Now if the loop stored a non-nullptr to %a, we could cause a nullptr
1801 // dereference by skipping over loop iterations.
1802 if (const auto *CB = dyn_cast<CallBase>(&I)) {
1803 if (CB->onlyAccessesInaccessibleMemory())
1804 return true;
1805 }
1806 return isa<UnreachableInst>(I);
1807 });
1808}
1809
1810bool IndVarSimplify::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1811 SmallVector<BasicBlock*, 16> ExitingBlocks;
1812 L->getExitingBlocks(ExitingBlocks);
1813
1814 // Finally, see if we can rewrite our exit conditions into a loop invariant
1815 // form. If we have a read-only loop, and we can tell that we must exit down
1816 // a path which does not need any of the values computed within the loop, we
1817 // can rewrite the loop to exit on the first iteration. Note that this
1818 // doesn't either a) tell us the loop exits on the first iteration (unless
1819 // *all* exits are predicateable) or b) tell us *which* exit might be taken.
1820 // This transformation looks a lot like a restricted form of dead loop
1821 // elimination, but restricted to read-only loops and without neccesssarily
1822 // needing to kill the loop entirely.
1823 if (!Opts.indvars_predicate_loops)
1824 return false;
1825
1826 // Note: ExactBTC is the exact backedge taken count *iff* the loop exits
1827 // through *explicit* control flow. We have to eliminate the possibility of
1828 // implicit exits (see below) before we know it's truly exact.
1829 const SCEV *ExactBTC = SE->getBackedgeTakenCount(L);
1830 if (isa<SCEVCouldNotCompute>(ExactBTC) || !Rewriter.isSafeToExpand(ExactBTC))
1831 return false;
1832
1833 assert(SE->isLoopInvariant(ExactBTC, L) && "BTC must be loop invariant");
1834 assert(ExactBTC->getType()->isIntegerTy() && "BTC must be integer");
1835
1836 auto BadExit = [&](BasicBlock *ExitingBB) {
1837 // If our exiting block exits multiple loops, we can only rewrite the
1838 // innermost one. Otherwise, we're changing how many times the innermost
1839 // loop runs before it exits.
1840 if (LI->getLoopFor(ExitingBB) != L)
1841 return true;
1842
1843 // Can't rewrite non-branch yet.
1844 CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1845 if (!BI)
1846 return true;
1847
1848 // If already constant, nothing to do.
1849 if (isa<Constant>(BI->getCondition()))
1850 return true;
1851
1852 // If the exit block has phis, we need to be able to compute the values
1853 // within the loop which contains them. This assumes trivially lcssa phis
1854 // have already been removed; TODO: generalize
1855 BasicBlock *ExitBlock =
1856 BI->getSuccessor(L->contains(BI->getSuccessor(0)) ? 1 : 0);
1857 if (!ExitBlock->phis().empty())
1858 return true;
1859
1860 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1861 if (isa<SCEVCouldNotCompute>(ExitCount) ||
1862 !Rewriter.isSafeToExpand(ExitCount))
1863 return true;
1864
1865 assert(SE->isLoopInvariant(ExitCount, L) &&
1866 "Exit count must be loop invariant");
1867 assert(ExitCount->getType()->isIntegerTy() && "Exit count must be integer");
1868 return false;
1869 };
1870
1871 // Make sure all exits dominate the latch. This means there is a linear chain
1872 // of exits. We check this before sorting so we have a total order.
1873 BasicBlock *Latch = L->getLoopLatch();
1874 for (BasicBlock *ExitingBB : ExitingBlocks)
1875 if (!DT->dominates(ExitingBB, Latch))
1876 return false;
1877
1878 // If we have any exits which can't be predicated themselves, than we can't
1879 // predicate any exit which isn't guaranteed to execute before it. Consider
1880 // two exits (a) and (b) which would both exit on the same iteration. If we
1881 // can predicate (b), but not (a), and (a) preceeds (b) along some path, then
1882 // we could convert a loop from exiting through (a) to one exiting through
1883 // (b). Note that this problem exists only for exits with the same exit
1884 // count, and we could be more aggressive when exit counts are known inequal.
1885 llvm::sort(ExitingBlocks, [&](BasicBlock *A, BasicBlock *B) {
1886 // llvm::sort sorts in ascending order, so we want the inverse of
1887 // the normal dominance relation.
1888 if (A == B)
1889 return false;
1890 if (DT->properlyDominates(A, B))
1891 return true;
1892 if (DT->properlyDominates(B, A))
1893 return false;
1894 llvm_unreachable("Should have total dominance order");
1895 });
1896
1897 // Make sure our exit blocks are really a total order (i.e. a linear chain of
1898 // exits before the backedge).
1899 for (unsigned i = 1; i < ExitingBlocks.size(); i++)
1900 assert(DT->dominates(ExitingBlocks[i - 1], ExitingBlocks[i]) &&
1901 "Not sorted by dominance");
1902
1903 // Given our sorted total order, we know that exit[j] must be evaluated
1904 // after all exit[i] such j > i.
1905 for (unsigned i = 0, e = ExitingBlocks.size(); i < e; i++)
1906 if (BadExit(ExitingBlocks[i])) {
1907 ExitingBlocks.resize(i);
1908 break;
1909 }
1910
1911 if (ExitingBlocks.empty())
1912 return false;
1913
1914 // At this point, ExitingBlocks consists of only those blocks which are
1915 // predicatable. Given that, we know we have at least one exit we can
1916 // predicate if the loop is doesn't have side effects and doesn't have any
1917 // implicit exits (because then our exact BTC isn't actually exact).
1918 // @Reviewers - As structured, this is O(I^2) for loop nests. Any
1919 // suggestions on how to improve this? I can obviously bail out for outer
1920 // loops, but that seems less than ideal. MemorySSA can find memory writes,
1921 // is that enough for *all* side effects?
1922 bool HasThreadLocalSideEffects = false;
1923 for (BasicBlock *BB : L->blocks())
1924 for (auto &I : *BB) {
1925 // TODO:isGuaranteedToTransfer
1926 if (I.mayHaveSideEffects()) {
1927 if (!Opts.indvars_predicate_loop_traps)
1928 return false;
1929 HasThreadLocalSideEffects = true;
1930 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1931 // Simple stores cannot be observed by other threads.
1932 // If HasThreadLocalSideEffects is set, we check
1933 // crashingBBWithoutEffect to make sure that the crashing BB cannot
1934 // observe them either.
1935 if (!SI->isSimple())
1936 return false;
1937 } else {
1938 return false;
1939 }
1940 }
1941
1942 // Skip if the loop has tokens referenced outside the loop to avoid
1943 // changing convergence behavior.
1944 if (I.getType()->isTokenTy()) {
1945 for (User *U : I.users()) {
1946 Instruction *UserInst = dyn_cast<Instruction>(U);
1947 if (UserInst && !L->contains(UserInst)) {
1948 return false;
1949 }
1950 }
1951 }
1952 }
1953
1954 bool Changed = false;
1955 // Finally, do the actual predication for all predicatable blocks. A couple
1956 // of notes here:
1957 // 1) We don't bother to constant fold dominated exits with identical exit
1958 // counts; that's simply a form of CSE/equality propagation and we leave
1959 // it for dedicated passes.
1960 // 2) We insert the comparison at the branch. Hoisting introduces additional
1961 // legality constraints and we leave that to dedicated logic. We want to
1962 // predicate even if we can't insert a loop invariant expression as
1963 // peeling or unrolling will likely reduce the cost of the otherwise loop
1964 // varying check.
1965 Rewriter.setInsertPoint(L->getLoopPreheader()->getTerminator());
1966 IRBuilder<> B(L->getLoopPreheader()->getTerminator());
1967 Value *ExactBTCV = nullptr; // Lazily generated if needed.
1968 for (BasicBlock *ExitingBB : ExitingBlocks) {
1969 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1970
1971 auto *BI = cast<CondBrInst>(ExitingBB->getTerminator());
1972 if (HasThreadLocalSideEffects) {
1973 const BasicBlock *Unreachable = nullptr;
1974 for (const BasicBlock *Succ : BI->successors()) {
1975 if (isa<UnreachableInst>(Succ->getTerminator()))
1976 Unreachable = Succ;
1977 }
1978 // Exit BB which have one branch back into the loop and another one to
1979 // a trap can still be optimized, because local side effects cannot
1980 // be observed in the exit case (the trap). We could be smarter about
1981 // this, but for now lets pattern match common cases that directly trap.
1982 if (Unreachable == nullptr || !crashingBBWithoutEffect(*Unreachable))
1983 return Changed;
1984 }
1985 Value *NewCond;
1986 if (ExitCount == ExactBTC) {
1987 NewCond = L->contains(BI->getSuccessor(0)) ?
1988 B.getFalse() : B.getTrue();
1989 } else {
1990 Value *ECV = Rewriter.expandCodeFor(ExitCount);
1991 if (!ExactBTCV)
1992 ExactBTCV = Rewriter.expandCodeFor(ExactBTC);
1993 Value *RHS = ExactBTCV;
1994 if (ECV->getType() != RHS->getType()) {
1995 Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1996 ECV = B.CreateZExt(ECV, WiderTy);
1997 RHS = B.CreateZExt(RHS, WiderTy);
1998 }
1999 auto Pred = L->contains(BI->getSuccessor(0)) ?
2000 ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
2001 NewCond = B.CreateICmp(Pred, ECV, RHS);
2002 }
2003 Value *OldCond = BI->getCondition();
2004 BI->setCondition(NewCond);
2005 if (OldCond->use_empty())
2006 DeadInsts.emplace_back(OldCond);
2007 Changed = true;
2008 RunUnswitching = true;
2009 }
2010
2011 return Changed;
2012}
2013
2014//===----------------------------------------------------------------------===//
2015// IndVarSimplify driver. Manage several subpasses of IV simplification.
2016//===----------------------------------------------------------------------===//
2017
2018bool IndVarSimplify::run(Loop *L) {
2019 // We need (and expect!) the incoming loop to be in LCSSA.
2020 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2021 "LCSSA required to run indvars!");
2022
2023 // If LoopSimplify form is not available, stay out of trouble. Some notes:
2024 // - LSR currently only supports LoopSimplify-form loops. Indvars'
2025 // canonicalization can be a pessimization without LSR to "clean up"
2026 // afterwards.
2027 // - We depend on having a preheader; in particular,
2028 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2029 // and we're in trouble if we can't find the induction variable even when
2030 // we've manually inserted one.
2031 // - LFTR relies on having a single backedge.
2032 if (!L->isLoopSimplifyForm())
2033 return false;
2034
2035 bool Changed = false;
2036 // If there are any floating-point recurrences, attempt to
2037 // transform them to use integer recurrences.
2038 Changed |= rewriteNonIntegerIVs(L);
2039
2040 // Create a rewriter object which we'll use to transform the code with.
2041 SCEVExpander Rewriter(*SE, "indvars");
2042#if LLVM_ENABLE_ABI_BREAKING_CHECKS
2043 Rewriter.setDebugType(DEBUG_TYPE);
2044#endif
2045
2046 // Eliminate redundant IV users.
2047 //
2048 // Simplification works best when run before other consumers of SCEV. We
2049 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2050 // other expressions involving loop IVs have been evaluated. This helps SCEV
2051 // set no-wrap flags before normalizing sign/zero extension.
2052 Rewriter.disableCanonicalMode();
2053 Changed |= simplifyAndExtend(L, Rewriter, LI);
2054
2055 // Check to see if we can compute the final value of any expressions
2056 // that are recurrent in the loop, and substitute the exit values from the
2057 // loop into any instructions outside of the loop that use the final values
2058 // of the current expressions.
2059 if (Opts.replexitval != NeverRepl) {
2060 if (int Rewrites = rewriteLoopExitValues(L, LI, TLI, SE, TTI, Rewriter, DT,
2061 Opts.replexitval, DeadInsts)) {
2062 NumReplaced += Rewrites;
2063 Changed = true;
2064 }
2065 }
2066
2067 // Eliminate redundant IV cycles.
2068 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts, TTI);
2069
2070 // Try to convert exit conditions to unsigned and rotate computation
2071 // out of the loop. Note: Handles invalidation internally if needed.
2072 Changed |= canonicalizeExitCondition(L);
2073
2074 // Try to eliminate loop exits based on analyzeable exit counts
2075 if (optimizeLoopExits(L, Rewriter)) {
2076 Changed = true;
2077 // Given we've changed exit counts, notify SCEV
2078 // Some nested loops may share same folded exit basic block,
2079 // thus we need to notify top most loop.
2080 SE->forgetTopmostLoop(L);
2081 }
2082
2083 // Try to form loop invariant tests for loop exits by changing how many
2084 // iterations of the loop run when that is unobservable.
2085 if (predicateLoopExits(L, Rewriter)) {
2086 Changed = true;
2087 // Given we've changed exit counts, notify SCEV
2088 SE->forgetLoop(L);
2089 }
2090
2091 // If we have a trip count expression, rewrite the loop's exit condition
2092 // using it.
2093 if (!Opts.disable_lftr) {
2094 BasicBlock *PreHeader = L->getLoopPreheader();
2095
2096 SmallVector<BasicBlock*, 16> ExitingBlocks;
2097 L->getExitingBlocks(ExitingBlocks);
2098 for (BasicBlock *ExitingBB : ExitingBlocks) {
2099 // Can't rewrite non-branch yet.
2100 if (!isa<CondBrInst>(ExitingBB->getTerminator()))
2101 continue;
2102
2103 // If our exitting block exits multiple loops, we can only rewrite the
2104 // innermost one. Otherwise, we're changing how many times the innermost
2105 // loop runs before it exits.
2106 if (LI->getLoopFor(ExitingBB) != L)
2107 continue;
2108
2109 if (!needsLFTR(L, ExitingBB))
2110 continue;
2111
2112 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2113 if (isa<SCEVCouldNotCompute>(ExitCount))
2114 continue;
2115
2116 // This was handled above, but as we form SCEVs, we can sometimes refine
2117 // existing ones; this allows exit counts to be folded to zero which
2118 // weren't when optimizeLoopExits saw them. Arguably, we should iterate
2119 // until stable to handle cases like this better.
2120 if (ExitCount->isZero())
2121 continue;
2122
2123 PHINode *IndVar = FindLoopCounter(L, ExitingBB, ExitCount, SE, DT);
2124 if (!IndVar)
2125 continue;
2126
2127 // Avoid high cost expansions. Note: This heuristic is questionable in
2128 // that our definition of "high cost" is not exactly principled.
2129 if (Rewriter.isHighCostExpansion(ExitCount, L, SCEVCheapExpansionBudget,
2130 TTI, PreHeader->getTerminator()))
2131 continue;
2132
2133 if (!Rewriter.isSafeToExpand(ExitCount))
2134 continue;
2135
2136 Changed |= linearFunctionTestReplace(L, ExitingBB,
2137 ExitCount, IndVar,
2138 Rewriter);
2139 }
2140 }
2141 // Clear the rewriter cache, because values that are in the rewriter's cache
2142 // can be deleted in the loop below, causing the AssertingVH in the cache to
2143 // trigger.
2144 Rewriter.clear();
2145
2146 // Now that we're done iterating through lists, clean up any instructions
2147 // which are now dead.
2148 while (!DeadInsts.empty()) {
2149 Value *V = DeadInsts.pop_back_val();
2150
2151 if (PHINode *PHI = dyn_cast_or_null<PHINode>(V))
2152 Changed |= RecursivelyDeleteDeadPHINode(PHI, TLI, MSSAU.get());
2153 else if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
2154 Changed |=
2155 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI, MSSAU.get());
2156 }
2157
2158 // The Rewriter may not be used from this point on.
2159
2160 // Loop-invariant instructions in the preheader that aren't used in the
2161 // loop may be sunk below the loop to reduce register pressure.
2162 Changed |= sinkUnusedInvariants(L);
2163
2164 // rewriteFirstIterationLoopExitValues does not rely on the computation of
2165 // trip count and therefore can further simplify exit values in addition to
2166 // rewriteLoopExitValues.
2167 Changed |= rewriteFirstIterationLoopExitValues(L);
2168
2169 // Clean up dead instructions.
2170 Changed |= DeleteDeadPHIs(L->getHeader(), TLI, MSSAU.get());
2171
2172 // Check a post-condition.
2173 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2174 "Indvars did not preserve LCSSA!");
2175 if (VerifyMemorySSA && MSSAU)
2176 MSSAU->getMemorySSA()->verifyMemorySSA();
2177
2178 return Changed;
2179}
2180
2183 LPMUpdater &) {
2184 Function *F = L.getHeader()->getParent();
2185 const DataLayout &DL = F->getDataLayout();
2186 const ScalarOptions &Opts = ScalarOptions::Global;
2187
2188 IndVarSimplify IVS(Opts, &AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI,
2189 AR.MSSA, WidenIndVars && Opts.indvars_widen_indvars);
2190 if (!IVS.run(&L))
2191 return PreservedAnalyses::all();
2192
2193 auto PA = getLoopPassPreservedAnalyses();
2194 PA.preserveSet<CFGAnalyses>();
2195 if (IVS.runUnswitching()) {
2197 PA.preserve<ShouldRunExtraSimpleLoopUnswitch>();
2198 }
2199
2200 if (AR.MSSA)
2201 PA.preserve<MemorySSAAnalysis>();
2202 return PA;
2203}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AArch64 Predicate As Counter Loop Rewrites
unsigned uint64_t
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool optimizeLoopExitWithUnknownExitCount(const Loop *L, CondBrInst *BI, BasicBlock *ExitingBB, const SCEV *MaxIter, bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static Value * genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB, const SCEV *ExitCount, bool UsePostInc, Loop *L, SCEVExpander &Rewriter, ScalarEvolution *SE)
Insert an IR expression which computes the value held by the IV IndVar (which must be an loop counter...
static std::optional< FloatingPointIV > maybeFloatingPointRecurrence(Loop *L, PHINode *PN)
Analyze a PN to determine whether it represents a simple floating-point induction variable,...
static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB)
Whether the current loop exit test is based on this value.
static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, const TargetTransformInfo *TTI)
Update information about the induction variable that is extended by this sign or zero extend operatio...
static bool isRepresentableAsExactInteger(const APFloat &FPVal, int64_t IntVal)
Ensure we stay within the bounds of fp values that can be represented as integers without gaps,...
static void replaceLoopPHINodesWithPreheaderValues(LoopInfo *LI, Loop *L, SmallVectorImpl< WeakTrackingVH > &DeadInsts, ScalarEvolution &SE)
static void replaceExitCond(CondBrInst *BI, Value *NewCond, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static bool needsLFTR(Loop *L, BasicBlock *ExitingBB)
linearFunctionTestReplace policy.
static Value * createInvariantCond(const Loop *L, BasicBlock *ExitingBB, const ScalarEvolution::LoopInvariantPredicate &LIP, SCEVExpander &Rewriter)
static bool isLoopCounter(PHINode *Phi, Loop *L, ScalarEvolution *SE)
Return true if the given phi is a "counter" in L.
static std::optional< Value * > createReplacement(ICmpInst *ICmp, const Loop *L, BasicBlock *ExitingBB, const SCEV *MaxIter, bool Inverted, bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter)
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl< Value * > &Visited, unsigned Depth)
Recursive helper for hasConcreteDef().
static bool hasConcreteDef(Value *V)
Return true if the given value is concrete.
static void foldExit(const Loop *L, BasicBlock *ExitingBB, bool IsTaken, SmallVectorImpl< WeakTrackingVH > &DeadInsts)
static PHINode * getLoopPhiForCounter(Value *IncV, Loop *L)
Given an Value which is hoped to be part of an add recurance in the given loop, return the associated...
static Constant * createFoldedExitCond(const Loop *L, BasicBlock *ExitingBB, bool IsTaken)
static std::optional< IntegerIV > tryConvertToIntegerIV(const FloatingPointIV &FPIV)
Ensure that the floating-point IV can be converted to a semantics-preserving signed 32-bit integer IV...
static void canonicalizeToIntegerIV(Loop *L, PHINode *PN, const FloatingPointIV &FPIV, const IntegerIV &IIV, const TargetLibraryInfo *TLI, std::unique_ptr< MemorySSAUpdater > &MSSAU)
Rewrite the floating-point IV as an integer IV.
static PHINode * FindLoopCounter(Loop *L, BasicBlock *ExitingBB, const SCEV *BECount, ScalarEvolution *SE, DominatorTree *DT)
Search the loop header for a loop counter (anadd rec w/step of one) suitable for use by LFTR.
static bool crashingBBWithoutEffect(const BasicBlock &BB)
static CmpInst::Predicate getIntegerPredicate(CmpInst::Predicate FPPred)
static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal)
Convert APF to an integer, if possible.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI StringRef getPredicateName(Predicate P)
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator_range< succ_iterator > successors()
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU.
Definition DataLayout.h:242
static DebugLoc getDropped()
Definition DebugLoc.h:155
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction compares its operands according to the predicate given to the constructor.
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Instruction * user_back()
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:466
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static unsigned getIncomingValueNumForOperand(unsigned i)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
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.
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
This class represents a cast from signed integer to floating point.
The main scalar evolution driver.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
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.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
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 void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
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,...
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
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:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Value handle that is nullable, but tries to track the Value.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:520
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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.
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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 RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:620
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_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...
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
DWARFExpression::Operation Op
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:587
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
LLVM_ABI bool isAlmostDeadIV(PHINode *IV, BasicBlock *LatchBlock, Value *Cond)
Return true if the induction variable IV in a Loop whose latch is LatchBlock would become dead if the...
LLVM_ABI int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, ScalarEvolution *SE, const TargetTransformInfo *TTI, SCEVExpander &Rewriter, DominatorTree *DT, ReplaceExitVal ReplaceExitValue, SmallVector< WeakTrackingVH, 16 > &DeadInsts)
If the final value of any expressions that are recurrent in the loop can be computed,...
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
@ NeverRepl
Definition LoopUtils.h:601
SCEVUseT< const SCEV * > SCEVUse
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
Represents a floating-point induction variable pattern that may be convertible to integer form.
FloatingPointIV(APFloat Init, APFloat Incr, APFloat Exit, FCmpInst *Compare, BinaryOperator *Add)
BinaryOperator * Add
Represents the integer values for a converted IV.
int64_t InitValue
int64_t ExitValue
int64_t IncrValue
CmpInst::Predicate NewPred
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A marker analysis to determine if SimpleLoopUnswitch should run again on a given loop.
Collect information about induction variables that are used by sign/zero extend operations.