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