LLVM 18.0.0git
InductiveRangeCheckElimination.cpp
Go to the documentation of this file.
1//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
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// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//
43//===----------------------------------------------------------------------===//
44
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/StringRef.h"
52#include "llvm/ADT/Twine.h"
59#include "llvm/IR/BasicBlock.h"
60#include "llvm/IR/CFG.h"
61#include "llvm/IR/Constants.h"
63#include "llvm/IR/Dominators.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/IRBuilder.h"
66#include "llvm/IR/InstrTypes.h"
68#include "llvm/IR/Metadata.h"
69#include "llvm/IR/Module.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/User.h"
74#include "llvm/IR/Value.h"
79#include "llvm/Support/Debug.h"
89#include <algorithm>
90#include <cassert>
91#include <iterator>
92#include <limits>
93#include <optional>
94#include <utility>
95
96using namespace llvm;
97using namespace llvm::PatternMatch;
98
99static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
100 cl::init(64));
101
102static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
103 cl::init(false));
104
105static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
106 cl::init(false));
107
108static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
109 cl::Hidden, cl::init(false));
110
111static cl::opt<unsigned> MinRuntimeIterations("irce-min-runtime-iterations",
112 cl::Hidden, cl::init(10));
113
114static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
115 cl::Hidden, cl::init(true));
116
118 "irce-allow-narrow-latch", cl::Hidden, cl::init(true),
119 cl::desc("If set to true, IRCE may eliminate wide range checks in loops "
120 "with narrow latch condition."));
121
123 "irce-max-type-size-for-overflow-check", cl::Hidden, cl::init(32),
124 cl::desc(
125 "Maximum size of range check type for which can be produced runtime "
126 "overflow check of its limit's computation"));
127
128static cl::opt<bool>
129 PrintScaledBoundaryRangeChecks("irce-print-scaled-boundary-range-checks",
130 cl::Hidden, cl::init(false));
131
132#define DEBUG_TYPE "irce"
133
134namespace {
135
136/// An inductive range check is conditional branch in a loop with
137///
138/// 1. a very cold successor (i.e. the branch jumps to that successor very
139/// rarely)
140///
141/// and
142///
143/// 2. a condition that is provably true for some contiguous range of values
144/// taken by the containing loop's induction variable.
145///
146class InductiveRangeCheck {
147
148 const SCEV *Begin = nullptr;
149 const SCEV *Step = nullptr;
150 const SCEV *End = nullptr;
151 Use *CheckUse = nullptr;
152
153 static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
154 const SCEVAddRecExpr *&Index,
155 const SCEV *&End);
156
157 static void
158 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
160 SmallPtrSetImpl<Value *> &Visited);
161
162 static bool parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,
164 const SCEVAddRecExpr *&Index,
165 const SCEV *&End);
166
167 static bool reassociateSubLHS(Loop *L, Value *VariantLHS, Value *InvariantRHS,
169 const SCEVAddRecExpr *&Index, const SCEV *&End);
170
171public:
172 const SCEV *getBegin() const { return Begin; }
173 const SCEV *getStep() const { return Step; }
174 const SCEV *getEnd() const { return End; }
175
176 void print(raw_ostream &OS) const {
177 OS << "InductiveRangeCheck:\n";
178 OS << " Begin: ";
179 Begin->print(OS);
180 OS << " Step: ";
181 Step->print(OS);
182 OS << " End: ";
183 End->print(OS);
184 OS << "\n CheckUse: ";
185 getCheckUse()->getUser()->print(OS);
186 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
187 }
188
190 void dump() {
191 print(dbgs());
192 }
193
194 Use *getCheckUse() const { return CheckUse; }
195
196 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
197 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
198
199 class Range {
200 const SCEV *Begin;
201 const SCEV *End;
202
203 public:
204 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
205 assert(Begin->getType() == End->getType() && "ill-typed range!");
206 }
207
208 Type *getType() const { return Begin->getType(); }
209 const SCEV *getBegin() const { return Begin; }
210 const SCEV *getEnd() const { return End; }
211 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
212 if (Begin == End)
213 return true;
214 if (IsSigned)
215 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
216 else
217 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
218 }
219 };
220
221 /// This is the value the condition of the branch needs to evaluate to for the
222 /// branch to take the hot successor (see (1) above).
223 bool getPassingDirection() { return true; }
224
225 /// Computes a range for the induction variable (IndVar) in which the range
226 /// check is redundant and can be constant-folded away. The induction
227 /// variable is not required to be the canonical {0,+,1} induction variable.
228 std::optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
229 const SCEVAddRecExpr *IndVar,
230 bool IsLatchSigned) const;
231
232 /// Parse out a set of inductive range checks from \p BI and append them to \p
233 /// Checks.
234 ///
235 /// NB! There may be conditions feeding into \p BI that aren't inductive range
236 /// checks, and hence don't end up in \p Checks.
237 static void extractRangeChecksFromBranch(
239 SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed);
240};
241
242class InductiveRangeCheckElimination {
243 ScalarEvolution &SE;
245 DominatorTree &DT;
246 LoopInfo &LI;
247
248 using GetBFIFunc =
250 GetBFIFunc GetBFI;
251
252 // Returns true if it is profitable to do a transform basing on estimation of
253 // number of iterations.
254 bool isProfitableToTransform(const Loop &L, LoopStructure &LS);
255
256public:
257 InductiveRangeCheckElimination(ScalarEvolution &SE,
259 LoopInfo &LI, GetBFIFunc GetBFI = std::nullopt)
260 : SE(SE), BPI(BPI), DT(DT), LI(LI), GetBFI(GetBFI) {}
261
262 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
263};
264
265} // end anonymous namespace
266
267/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
268/// be interpreted as a range check, return false. Otherwise set `Index` to the
269/// SCEV being range checked, and set `End` to the upper or lower limit `Index`
270/// is being range checked.
271bool InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
272 ScalarEvolution &SE,
273 const SCEVAddRecExpr *&Index,
274 const SCEV *&End) {
275 auto IsLoopInvariant = [&SE, L](Value *V) {
276 return SE.isLoopInvariant(SE.getSCEV(V), L);
277 };
278
279 ICmpInst::Predicate Pred = ICI->getPredicate();
280 Value *LHS = ICI->getOperand(0);
281 Value *RHS = ICI->getOperand(1);
282
283 // Canonicalize to the `Index Pred Invariant` comparison
284 if (IsLoopInvariant(LHS)) {
285 std::swap(LHS, RHS);
286 Pred = CmpInst::getSwappedPredicate(Pred);
287 } else if (!IsLoopInvariant(RHS))
288 // Both LHS and RHS are loop variant
289 return false;
290
291 if (parseIvAgaisntLimit(L, LHS, RHS, Pred, SE, Index, End))
292 return true;
293
294 if (reassociateSubLHS(L, LHS, RHS, Pred, SE, Index, End))
295 return true;
296
297 // TODO: support ReassociateAddLHS
298 return false;
299}
300
301// Try to parse range check in the form of "IV vs Limit"
302bool InductiveRangeCheck::parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,
304 ScalarEvolution &SE,
305 const SCEVAddRecExpr *&Index,
306 const SCEV *&End) {
307
308 auto SIntMaxSCEV = [&](Type *T) {
309 unsigned BitWidth = cast<IntegerType>(T)->getBitWidth();
311 };
312
313 const auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(LHS));
314 if (!AddRec)
315 return false;
316
317 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
318 // We can potentially do much better here.
319 // If we want to adjust upper bound for the unsigned range check as we do it
320 // for signed one, we will need to pick Unsigned max
321 switch (Pred) {
322 default:
323 return false;
324
325 case ICmpInst::ICMP_SGE:
326 if (match(RHS, m_ConstantInt<0>())) {
327 Index = AddRec;
328 End = SIntMaxSCEV(Index->getType());
329 return true;
330 }
331 return false;
332
333 case ICmpInst::ICMP_SGT:
334 if (match(RHS, m_ConstantInt<-1>())) {
335 Index = AddRec;
336 End = SIntMaxSCEV(Index->getType());
337 return true;
338 }
339 return false;
340
341 case ICmpInst::ICMP_SLT:
342 case ICmpInst::ICMP_ULT:
343 Index = AddRec;
344 End = SE.getSCEV(RHS);
345 return true;
346
347 case ICmpInst::ICMP_SLE:
348 case ICmpInst::ICMP_ULE:
349 const SCEV *One = SE.getOne(RHS->getType());
350 const SCEV *RHSS = SE.getSCEV(RHS);
351 bool Signed = Pred == ICmpInst::ICMP_SLE;
352 if (SE.willNotOverflow(Instruction::BinaryOps::Add, Signed, RHSS, One)) {
353 Index = AddRec;
354 End = SE.getAddExpr(RHSS, One);
355 return true;
356 }
357 return false;
358 }
359
360 llvm_unreachable("default clause returns!");
361}
362
363// Try to parse range check in the form of "IV - Offset vs Limit" or "Offset -
364// IV vs Limit"
365bool InductiveRangeCheck::reassociateSubLHS(
366 Loop *L, Value *VariantLHS, Value *InvariantRHS, ICmpInst::Predicate Pred,
367 ScalarEvolution &SE, const SCEVAddRecExpr *&Index, const SCEV *&End) {
368 Value *LHS, *RHS;
369 if (!match(VariantLHS, m_Sub(m_Value(LHS), m_Value(RHS))))
370 return false;
371
372 const SCEV *IV = SE.getSCEV(LHS);
373 const SCEV *Offset = SE.getSCEV(RHS);
374 const SCEV *Limit = SE.getSCEV(InvariantRHS);
375
376 bool OffsetSubtracted = false;
377 if (SE.isLoopInvariant(IV, L))
378 // "Offset - IV vs Limit"
380 else if (SE.isLoopInvariant(Offset, L))
381 // "IV - Offset vs Limit"
382 OffsetSubtracted = true;
383 else
384 return false;
385
386 const auto *AddRec = dyn_cast<SCEVAddRecExpr>(IV);
387 if (!AddRec)
388 return false;
389
390 // In order to turn "IV - Offset < Limit" into "IV < Limit + Offset", we need
391 // to be able to freely move values from left side of inequality to right side
392 // (just as in normal linear arithmetics). Overflows make things much more
393 // complicated, so we want to avoid this.
394 //
395 // Let's prove that the initial subtraction doesn't overflow with all IV's
396 // values from the safe range constructed for that check.
397 //
398 // [Case 1] IV - Offset < Limit
399 // It doesn't overflow if:
400 // SINT_MIN <= IV - Offset <= SINT_MAX
401 // In terms of scaled SINT we need to prove:
402 // SINT_MIN + Offset <= IV <= SINT_MAX + Offset
403 // Safe range will be constructed:
404 // 0 <= IV < Limit + Offset
405 // It means that 'IV - Offset' doesn't underflow, because:
406 // SINT_MIN + Offset < 0 <= IV
407 // and doesn't overflow:
408 // IV < Limit + Offset <= SINT_MAX + Offset
409 //
410 // [Case 2] Offset - IV > Limit
411 // It doesn't overflow if:
412 // SINT_MIN <= Offset - IV <= SINT_MAX
413 // In terms of scaled SINT we need to prove:
414 // -SINT_MIN >= IV - Offset >= -SINT_MAX
415 // Offset - SINT_MIN >= IV >= Offset - SINT_MAX
416 // Safe range will be constructed:
417 // 0 <= IV < Offset - Limit
418 // It means that 'Offset - IV' doesn't underflow, because
419 // Offset - SINT_MAX < 0 <= IV
420 // and doesn't overflow:
421 // IV < Offset - Limit <= Offset - SINT_MIN
422 //
423 // For the computed upper boundary of the IV's range (Offset +/- Limit) we
424 // don't know exactly whether it overflows or not. So if we can't prove this
425 // fact at compile time, we scale boundary computations to a wider type with
426 // the intention to add runtime overflow check.
427
428 auto getExprScaledIfOverflow = [&](Instruction::BinaryOps BinOp,
429 const SCEV *LHS,
430 const SCEV *RHS) -> const SCEV * {
431 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
432 SCEV::NoWrapFlags, unsigned);
433 switch (BinOp) {
434 default:
435 llvm_unreachable("Unsupported binary op");
436 case Instruction::Add:
438 break;
439 case Instruction::Sub:
441 break;
442 }
443
444 if (SE.willNotOverflow(BinOp, ICmpInst::isSigned(Pred), LHS, RHS,
445 cast<Instruction>(VariantLHS)))
446 return (SE.*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0);
447
448 // We couldn't prove that the expression does not overflow.
449 // Than scale it to a wider type to check overflow at runtime.
450 auto *Ty = cast<IntegerType>(LHS->getType());
451 if (Ty->getBitWidth() > MaxTypeSizeForOverflowCheck)
452 return nullptr;
453
454 auto WideTy = IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
455 return (SE.*Operation)(SE.getSignExtendExpr(LHS, WideTy),
456 SE.getSignExtendExpr(RHS, WideTy), SCEV::FlagAnyWrap,
457 0);
458 };
459
460 if (OffsetSubtracted)
461 // "IV - Offset < Limit" -> "IV" < Offset + Limit
462 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Offset, Limit);
463 else {
464 // "Offset - IV > Limit" -> "IV" < Offset - Limit
465 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Sub, Offset, Limit);
466 Pred = ICmpInst::getSwappedPredicate(Pred);
467 }
468
469 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
470 // "Expr <= Limit" -> "Expr < Limit + 1"
471 if (Pred == ICmpInst::ICMP_SLE && Limit)
472 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Limit,
473 SE.getOne(Limit->getType()));
474 if (Limit) {
475 Index = AddRec;
476 End = Limit;
477 return true;
478 }
479 }
480 return false;
481}
482
483void InductiveRangeCheck::extractRangeChecksFromCond(
484 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
486 SmallPtrSetImpl<Value *> &Visited) {
487 Value *Condition = ConditionUse.get();
488 if (!Visited.insert(Condition).second)
489 return;
490
491 // TODO: Do the same for OR, XOR, NOT etc?
492 if (match(Condition, m_LogicalAnd(m_Value(), m_Value()))) {
493 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
494 Checks, Visited);
495 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
496 Checks, Visited);
497 return;
498 }
499
500 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
501 if (!ICI)
502 return;
503
504 const SCEV *End = nullptr;
505 const SCEVAddRecExpr *IndexAddRec = nullptr;
506 if (!parseRangeCheckICmp(L, ICI, SE, IndexAddRec, End))
507 return;
508
509 assert(IndexAddRec && "IndexAddRec was not computed");
510 assert(End && "End was not computed");
511
512 if ((IndexAddRec->getLoop() != L) || !IndexAddRec->isAffine())
513 return;
514
515 InductiveRangeCheck IRC;
516 IRC.End = End;
517 IRC.Begin = IndexAddRec->getStart();
518 IRC.Step = IndexAddRec->getStepRecurrence(SE);
519 IRC.CheckUse = &ConditionUse;
520 Checks.push_back(IRC);
521}
522
523void InductiveRangeCheck::extractRangeChecksFromBranch(
525 SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed) {
526 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
527 return;
528
529 unsigned IndexLoopSucc = L->contains(BI->getSuccessor(0)) ? 0 : 1;
530 assert(L->contains(BI->getSuccessor(IndexLoopSucc)) &&
531 "No edges coming to loop?");
532 BranchProbability LikelyTaken(15, 16);
533
534 if (!SkipProfitabilityChecks && BPI &&
535 BPI->getEdgeProbability(BI->getParent(), IndexLoopSucc) < LikelyTaken)
536 return;
537
538 // IRCE expects branch's true edge comes to loop. Invert branch for opposite
539 // case.
540 if (IndexLoopSucc != 0) {
541 IRBuilder<> Builder(BI);
542 InvertBranch(BI, Builder);
543 if (BPI)
545 Changed = true;
546 }
547
549 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
550 Checks, Visited);
551}
552
553/// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
554/// signed or unsigned extension of \p S to type \p Ty.
555static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,
556 bool Signed) {
557 return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty);
558}
559
560// Compute a safe set of limits for the main loop to run in -- effectively the
561// intersection of `Range' and the iteration space of the original loop.
562// Return std::nullopt if unable to compute the set of subranges.
563static std::optional<LoopConstrainer::SubRanges>
565 InductiveRangeCheck::Range &Range,
566 const LoopStructure &MainLoopStructure) {
567 auto *RTy = cast<IntegerType>(Range.getType());
568 // We only support wide range checks and narrow latches.
569 if (!AllowNarrowLatchCondition && RTy != MainLoopStructure.ExitCountTy)
570 return std::nullopt;
571 if (RTy->getBitWidth() < MainLoopStructure.ExitCountTy->getBitWidth())
572 return std::nullopt;
573
575
576 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
577 // I think we can be more aggressive here and make this nuw / nsw if the
578 // addition that feeds into the icmp for the latch's terminating branch is nuw
579 // / nsw. In any case, a wrapping 2's complement addition is safe.
580 const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart),
581 RTy, SE, IsSignedPredicate);
582 const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,
583 SE, IsSignedPredicate);
584
585 bool Increasing = MainLoopStructure.IndVarIncreasing;
586
587 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
588 // [Smallest, GreatestSeen] is the range of values the induction variable
589 // takes.
590
591 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
592
593 const SCEV *One = SE.getOne(RTy);
594 if (Increasing) {
595 Smallest = Start;
596 Greatest = End;
597 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
598 GreatestSeen = SE.getMinusSCEV(End, One);
599 } else {
600 // These two computations may sign-overflow. Here is why that is okay:
601 //
602 // We know that the induction variable does not sign-overflow on any
603 // iteration except the last one, and it starts at `Start` and ends at
604 // `End`, decrementing by one every time.
605 //
606 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
607 // induction variable is decreasing we know that the smallest value
608 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
609 //
610 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
611 // that case, `Clamp` will always return `Smallest` and
612 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
613 // will be an empty range. Returning an empty range is always safe.
614
615 Smallest = SE.getAddExpr(End, One);
616 Greatest = SE.getAddExpr(Start, One);
617 GreatestSeen = Start;
618 }
619
620 auto Clamp = [&SE, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
621 return IsSignedPredicate
622 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
623 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
624 };
625
626 // In some cases we can prove that we don't need a pre or post loop.
627 ICmpInst::Predicate PredLE =
628 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
629 ICmpInst::Predicate PredLT =
630 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
631
632 bool ProvablyNoPreloop =
633 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
634 if (!ProvablyNoPreloop)
635 Result.LowLimit = Clamp(Range.getBegin());
636
637 bool ProvablyNoPostLoop =
638 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
639 if (!ProvablyNoPostLoop)
640 Result.HighLimit = Clamp(Range.getEnd());
641
642 return Result;
643}
644
645/// Computes and returns a range of values for the induction variable (IndVar)
646/// in which the range check can be safely elided. If it cannot compute such a
647/// range, returns std::nullopt.
648std::optional<InductiveRangeCheck::Range>
649InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
650 const SCEVAddRecExpr *IndVar,
651 bool IsLatchSigned) const {
652 // We can deal when types of latch check and range checks don't match in case
653 // if latch check is more narrow.
654 auto *IVType = dyn_cast<IntegerType>(IndVar->getType());
655 auto *RCType = dyn_cast<IntegerType>(getBegin()->getType());
656 auto *EndType = dyn_cast<IntegerType>(getEnd()->getType());
657 // Do not work with pointer types.
658 if (!IVType || !RCType)
659 return std::nullopt;
660 if (IVType->getBitWidth() > RCType->getBitWidth())
661 return std::nullopt;
662
663 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
664 // variable, that may or may not exist as a real llvm::Value in the loop) and
665 // this inductive range check is a range check on the "C + D * I" ("C" is
666 // getBegin() and "D" is getStep()). We rewrite the value being range
667 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
668 //
669 // The actual inequalities we solve are of the form
670 //
671 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
672 //
673 // Here L stands for upper limit of the safe iteration space.
674 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
675 // overflows when calculating (0 - M) and (L - M) we, depending on type of
676 // IV's iteration space, limit the calculations by borders of the iteration
677 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
678 // If we figured out that "anything greater than (-M) is safe", we strengthen
679 // this to "everything greater than 0 is safe", assuming that values between
680 // -M and 0 just do not exist in unsigned iteration space, and we don't want
681 // to deal with overflown values.
682
683 if (!IndVar->isAffine())
684 return std::nullopt;
685
686 const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned);
687 const SCEVConstant *B = dyn_cast<SCEVConstant>(
688 NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned));
689 if (!B)
690 return std::nullopt;
691 assert(!B->isZero() && "Recurrence with zero step?");
692
693 const SCEV *C = getBegin();
694 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
695 if (D != B)
696 return std::nullopt;
697
698 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
699 unsigned BitWidth = RCType->getBitWidth();
702
703 // Subtract Y from X so that it does not go through border of the IV
704 // iteration space. Mathematically, it is equivalent to:
705 //
706 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
707 //
708 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
709 // any width of bit grid). But after we take min/max, the result is
710 // guaranteed to be within [INT_MIN, INT_MAX].
711 //
712 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
713 // values, depending on type of latch condition that defines IV iteration
714 // space.
715 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
716 // FIXME: The current implementation assumes that X is in [0, SINT_MAX].
717 // This is required to ensure that SINT_MAX - X does not overflow signed and
718 // that X - Y does not overflow unsigned if Y is negative. Can we lift this
719 // restriction and make it work for negative X either?
720 if (IsLatchSigned) {
721 // X is a number from signed range, Y is interpreted as signed.
722 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
723 // thing we should care about is that we didn't cross SINT_MAX.
724 // So, if Y is positive, we subtract Y safely.
725 // Rule 1: Y > 0 ---> Y.
726 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
727 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
728 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
729 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
730 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
731 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
732 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
734 } else
735 // X is a number from unsigned range, Y is interpreted as signed.
736 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
737 // thing we should care about is that we didn't cross zero.
738 // So, if Y is negative, we subtract Y safely.
739 // Rule 1: Y <s 0 ---> Y.
740 // If 0 <= Y <= X, we subtract Y safely.
741 // Rule 2: Y <=s X ---> Y.
742 // If 0 <= X < Y, we should stop at 0 and can only subtract X.
743 // Rule 3: Y >s X ---> X.
744 // It gives us smin(X, Y) to subtract in all cases.
745 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
746 };
747 const SCEV *M = SE.getMinusSCEV(C, A);
748 const SCEV *Zero = SE.getZero(M->getType());
749
750 // This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
751 auto SCEVCheckNonNegative = [&](const SCEV *X) {
752 const Loop *L = IndVar->getLoop();
753 const SCEV *Zero = SE.getZero(X->getType());
754 const SCEV *One = SE.getOne(X->getType());
755 // Can we trivially prove that X is a non-negative or negative value?
756 if (isKnownNonNegativeInLoop(X, L, SE))
757 return One;
758 else if (isKnownNegativeInLoop(X, L, SE))
759 return Zero;
760 // If not, we will have to figure it out during the execution.
761 // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
762 const SCEV *NegOne = SE.getNegativeSCEV(One);
763 return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
764 };
765
766 // This function returns SCEV equal to 1 if X will not overflow in terms of
767 // range check type, 0 otherwise.
768 auto SCEVCheckWillNotOverflow = [&](const SCEV *X) {
769 // X doesn't overflow if SINT_MAX >= X.
770 // Then if (SINT_MAX - X) >= 0, X doesn't overflow
771 const SCEV *SIntMaxExt = SE.getSignExtendExpr(SIntMax, X->getType());
772 const SCEV *OverflowCheck =
773 SCEVCheckNonNegative(SE.getMinusSCEV(SIntMaxExt, X));
774
775 // X doesn't underflow if X >= SINT_MIN.
776 // Then if (X - SINT_MIN) >= 0, X doesn't underflow
777 const SCEV *SIntMinExt = SE.getSignExtendExpr(SIntMin, X->getType());
778 const SCEV *UnderflowCheck =
779 SCEVCheckNonNegative(SE.getMinusSCEV(X, SIntMinExt));
780
781 return SE.getMulExpr(OverflowCheck, UnderflowCheck);
782 };
783
784 // FIXME: Current implementation of ClampedSubtract implicitly assumes that
785 // X is non-negative (in sense of a signed value). We need to re-implement
786 // this function in a way that it will correctly handle negative X as well.
787 // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
788 // end up with a negative X and produce wrong results. So currently we ensure
789 // that if getEnd() is negative then both ends of the safe range are zero.
790 // Note that this may pessimize elimination of unsigned range checks against
791 // negative values.
792 const SCEV *REnd = getEnd();
793 const SCEV *EndWillNotOverflow = SE.getOne(RCType);
794
795 auto PrintRangeCheck = [&](raw_ostream &OS) {
796 auto L = IndVar->getLoop();
797 OS << "irce: in function ";
798 OS << L->getHeader()->getParent()->getName();
799 OS << ", in ";
800 L->print(OS);
801 OS << "there is range check with scaled boundary:\n";
802 print(OS);
803 };
804
805 if (EndType->getBitWidth() > RCType->getBitWidth()) {
806 assert(EndType->getBitWidth() == RCType->getBitWidth() * 2);
808 PrintRangeCheck(errs());
809 // End is computed with extended type but will be truncated to a narrow one
810 // type of range check. Therefore we need a check that the result will not
811 // overflow in terms of narrow type.
812 EndWillNotOverflow =
813 SE.getTruncateExpr(SCEVCheckWillNotOverflow(REnd), RCType);
814 REnd = SE.getTruncateExpr(REnd, RCType);
815 }
816
817 const SCEV *RuntimeChecks =
818 SE.getMulExpr(SCEVCheckNonNegative(REnd), EndWillNotOverflow);
819 const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), RuntimeChecks);
820 const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), RuntimeChecks);
821
822 return InductiveRangeCheck::Range(Begin, End);
823}
824
825static std::optional<InductiveRangeCheck::Range>
827 const std::optional<InductiveRangeCheck::Range> &R1,
828 const InductiveRangeCheck::Range &R2) {
829 if (R2.isEmpty(SE, /* IsSigned */ true))
830 return std::nullopt;
831 if (!R1)
832 return R2;
833 auto &R1Value = *R1;
834 // We never return empty ranges from this function, and R1 is supposed to be
835 // a result of intersection. Thus, R1 is never empty.
836 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
837 "We should never have empty R1!");
838
839 // TODO: we could widen the smaller range and have this work; but for now we
840 // bail out to keep things simple.
841 if (R1Value.getType() != R2.getType())
842 return std::nullopt;
843
844 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
845 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
846
847 // If the resulting range is empty, just return std::nullopt.
848 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
849 if (Ret.isEmpty(SE, /* IsSigned */ true))
850 return std::nullopt;
851 return Ret;
852}
853
854static std::optional<InductiveRangeCheck::Range>
856 const std::optional<InductiveRangeCheck::Range> &R1,
857 const InductiveRangeCheck::Range &R2) {
858 if (R2.isEmpty(SE, /* IsSigned */ false))
859 return std::nullopt;
860 if (!R1)
861 return R2;
862 auto &R1Value = *R1;
863 // We never return empty ranges from this function, and R1 is supposed to be
864 // a result of intersection. Thus, R1 is never empty.
865 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
866 "We should never have empty R1!");
867
868 // TODO: we could widen the smaller range and have this work; but for now we
869 // bail out to keep things simple.
870 if (R1Value.getType() != R2.getType())
871 return std::nullopt;
872
873 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
874 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
875
876 // If the resulting range is empty, just return std::nullopt.
877 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
878 if (Ret.isEmpty(SE, /* IsSigned */ false))
879 return std::nullopt;
880 return Ret;
881}
882
884 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
885 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
886 // There are no loops in the function. Return before computing other expensive
887 // analyses.
888 if (LI.empty())
889 return PreservedAnalyses::all();
890 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
891 auto &BPI = AM.getResult<BranchProbabilityAnalysis>(F);
892
893 // Get BFI analysis result on demand. Please note that modification of
894 // CFG invalidates this analysis and we should handle it.
895 auto getBFI = [&F, &AM ]()->BlockFrequencyInfo & {
897 };
898 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI, { getBFI });
899
900 bool Changed = false;
901 {
902 bool CFGChanged = false;
903 for (const auto &L : LI) {
904 CFGChanged |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr,
905 /*PreserveLCSSA=*/false);
906 Changed |= formLCSSARecursively(*L, DT, &LI, &SE);
907 }
908 Changed |= CFGChanged;
909
910 if (CFGChanged && !SkipProfitabilityChecks) {
913 AM.invalidate(F, PA);
914 }
915 }
916
918 appendLoopsToWorklist(LI, Worklist);
919 auto LPMAddNewLoop = [&Worklist](Loop *NL, bool IsSubloop) {
920 if (!IsSubloop)
921 appendLoopsToWorklist(*NL, Worklist);
922 };
923
924 while (!Worklist.empty()) {
925 Loop *L = Worklist.pop_back_val();
926 if (IRCE.run(L, LPMAddNewLoop)) {
927 Changed = true;
931 AM.invalidate(F, PA);
932 }
933 }
934 }
935
936 if (!Changed)
937 return PreservedAnalyses::all();
939}
940
941bool
942InductiveRangeCheckElimination::isProfitableToTransform(const Loop &L,
943 LoopStructure &LS) {
945 return true;
946 if (GetBFI) {
947 BlockFrequencyInfo &BFI = (*GetBFI)();
948 uint64_t hFreq = BFI.getBlockFreq(LS.Header).getFrequency();
949 uint64_t phFreq = BFI.getBlockFreq(L.getLoopPreheader()).getFrequency();
950 if (phFreq != 0 && hFreq != 0 && (hFreq / phFreq < MinRuntimeIterations)) {
951 LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "
952 << "the estimated number of iterations basing on "
953 "frequency info is " << (hFreq / phFreq) << "\n";);
954 return false;
955 }
956 return true;
957 }
958
959 if (!BPI)
960 return true;
961 BranchProbability ExitProbability =
962 BPI->getEdgeProbability(LS.Latch, LS.LatchBrExitIdx);
963 if (ExitProbability > BranchProbability(1, MinRuntimeIterations)) {
964 LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "
965 << "the exit probability is too big " << ExitProbability
966 << "\n";);
967 return false;
968 }
969 return true;
970}
971
972bool InductiveRangeCheckElimination::run(
973 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
974 if (L->getBlocks().size() >= LoopSizeCutoff) {
975 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
976 return false;
977 }
978
979 BasicBlock *Preheader = L->getLoopPreheader();
980 if (!Preheader) {
981 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
982 return false;
983 }
984
985 LLVMContext &Context = Preheader->getContext();
987 bool Changed = false;
988
989 for (auto *BBI : L->getBlocks())
990 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
991 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
992 RangeChecks, Changed);
993
994 if (RangeChecks.empty())
995 return Changed;
996
997 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
998 OS << "irce: looking at loop "; L->print(OS);
999 OS << "irce: loop has " << RangeChecks.size()
1000 << " inductive range checks: \n";
1001 for (InductiveRangeCheck &IRC : RangeChecks)
1002 IRC.print(OS);
1003 };
1004
1005 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
1006
1007 if (PrintRangeChecks)
1008 PrintRecognizedRangeChecks(errs());
1009
1010 const char *FailureReason = nullptr;
1011 std::optional<LoopStructure> MaybeLoopStructure =
1013 FailureReason);
1014 if (!MaybeLoopStructure) {
1015 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
1016 << FailureReason << "\n";);
1017 return Changed;
1018 }
1019 LoopStructure LS = *MaybeLoopStructure;
1020 if (!isProfitableToTransform(*L, LS))
1021 return Changed;
1022 const SCEVAddRecExpr *IndVar =
1023 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
1024
1025 std::optional<InductiveRangeCheck::Range> SafeIterRange;
1026
1027 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
1028 // Basing on the type of latch predicate, we interpret the IV iteration range
1029 // as signed or unsigned range. We use different min/max functions (signed or
1030 // unsigned) when intersecting this range with safe iteration ranges implied
1031 // by range checks.
1032 auto IntersectRange =
1033 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
1034
1035 for (InductiveRangeCheck &IRC : RangeChecks) {
1036 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1037 LS.IsSignedPredicate);
1038 if (Result) {
1039 auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result);
1040 if (MaybeSafeIterRange) {
1041 assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) &&
1042 "We should never return empty ranges!");
1043 RangeChecksToEliminate.push_back(IRC);
1044 SafeIterRange = *MaybeSafeIterRange;
1045 }
1046 }
1047 }
1048
1049 if (!SafeIterRange)
1050 return Changed;
1051
1052 std::optional<LoopConstrainer::SubRanges> MaybeSR =
1053 calculateSubRanges(SE, *L, *SafeIterRange, LS);
1054 if (!MaybeSR) {
1055 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
1056 return false;
1057 }
1058
1059 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1060 SafeIterRange->getBegin()->getType(), *MaybeSR);
1061
1062 if (LC.run()) {
1063 Changed = true;
1064
1065 auto PrintConstrainedLoopInfo = [L]() {
1066 dbgs() << "irce: in function ";
1067 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1068 dbgs() << "constrained ";
1069 L->print(dbgs());
1070 };
1071
1072 LLVM_DEBUG(PrintConstrainedLoopInfo());
1073
1075 PrintConstrainedLoopInfo();
1076
1077 // Optimize away the now-redundant range checks.
1078
1079 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1080 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1081 ? ConstantInt::getTrue(Context)
1083 IRC.getCheckUse()->set(FoldedRangeCheck);
1084 }
1085 }
1086
1087 return Changed;
1088}
This file implements a class to represent arbitrary precision integral constant values and operations...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:510
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define NL
bool End
Definition: ELF_riscv.cpp:478
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static const SCEV * NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE, bool Signed)
If the type of S matches with Ty, return S.
static cl::opt< bool > PrintRangeChecks("irce-print-range-checks", cl::Hidden, cl::init(false))
static cl::opt< bool > AllowUnsignedLatchCondition("irce-allow-unsigned-latch", cl::Hidden, cl::init(true))
static cl::opt< unsigned > MinRuntimeIterations("irce-min-runtime-iterations", cl::Hidden, cl::init(10))
static cl::opt< unsigned > LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, cl::init(64))
static std::optional< InductiveRangeCheck::Range > IntersectSignedRange(ScalarEvolution &SE, const std::optional< InductiveRangeCheck::Range > &R1, const InductiveRangeCheck::Range &R2)
static cl::opt< bool > AllowNarrowLatchCondition("irce-allow-narrow-latch", cl::Hidden, cl::init(true), cl::desc("If set to true, IRCE may eliminate wide range checks in loops " "with narrow latch condition."))
static cl::opt< unsigned > MaxTypeSizeForOverflowCheck("irce-max-type-size-for-overflow-check", cl::Hidden, cl::init(32), cl::desc("Maximum size of range check type for which can be produced runtime " "overflow check of its limit's computation"))
static cl::opt< bool > PrintChangedLoops("irce-print-changed-loops", cl::Hidden, cl::init(false))
static std::optional< InductiveRangeCheck::Range > IntersectUnsignedRange(ScalarEvolution &SE, const std::optional< InductiveRangeCheck::Range > &R1, const InductiveRangeCheck::Range &R2)
static cl::opt< bool > SkipProfitabilityChecks("irce-skip-profitability-checks", cl::Hidden, cl::init(false))
static std::optional< LoopConstrainer::SubRanges > calculateSubRanges(ScalarEvolution &SE, const Loop &L, InductiveRangeCheck::Range &Range, const LoopStructure &MainLoopStructure)
static cl::opt< bool > PrintScaledBoundaryRangeChecks("irce-print-scaled-boundary-range-checks", cl::Hidden, cl::init(false))
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition: MD5.cpp:55
#define R2(n)
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
LLVMContext & Context
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PowerPC Reduce CR logical Operation
This file provides a priority worklist.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This defines the Use class.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition: blake3_impl.h:78
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:187
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:649
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:803
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:207
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
void swapSuccEdgesProbabilities(const BasicBlock *Src)
Swap outgoing edges probabilities for Src with branch terminator.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:748
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:900
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:838
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:164
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2639
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const BasicBlock * getParent() const
Definition: Instruction.h:139
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:285
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:72
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
This class is used to constrain loops to run within a given iteration space.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:172
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:178
void abandon()
Mark an analysis as abandoned.
Definition: PassManager.h:226
bool empty() const
Determine if the PriorityWorklist is empty or not.
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
This class represents a constant integer value.
This class represents an analyzed expression in the program.
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
const SCEV * getSMaxExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getSMinExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?...
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * get() const
Definition: Use.h:66
const Use & getOperandUse(unsigned i) const
Definition: User.h:182
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:994
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition: DWP.cpp:456
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:425
void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
Definition: LoopUtils.cpp:1609
bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always negative in loop L.
Definition: LoopUtils.cpp:1183
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
Definition: LoopUtils.cpp:1190
static bool isProfitableToTransform(const Loop &L, const BranchInst *BI)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
IntegerType * ExitCountTy
static std::optional< LoopStructure > parseLoopStructure(ScalarEvolution &, Loop &, bool, const char *&)