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