1 //===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the guard widening pass. The semantics of the
11 // @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
12 // more often that it did before the transform. This optimization is called
13 // "widening" and can be used hoist and common runtime checks in situations like
16 // %cmp0 = 7 u< Length
17 // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
18 // call @unknown_side_effects()
19 // %cmp1 = 9 u< Length
20 // call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
25 // %cmp0 = 9 u< Length
26 // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
27 // call @unknown_side_effects()
30 // If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
31 // generic implementation of the same function, which will have the correct
32 // semantics from that point onward. It is always _legal_ to deoptimize (so
33 // replacing %cmp0 with false is "correct"), though it may not always be
34 // profitable to do so.
36 // NB! This pass is a work in progress. It hasn't been tuned to be "production
37 // ready" yet. It is known to have quadriatic running time and will not scale
38 // to large numbers of guards
40 //===----------------------------------------------------------------------===//
42 #include "llvm/Transforms/Scalar/GuardWidening.h"
43 #include "llvm/Pass.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/DepthFirstIterator.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Analysis/PostDominators.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/ConstantRange.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/PatternMatch.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Transforms/Scalar.h"
58 #define DEBUG_TYPE "guard-widening"
62 class GuardWideningImpl {
64 PostDominatorTree &PDT;
67 /// The set of guards whose conditions have been widened into dominating
69 SmallVector<IntrinsicInst *, 16> EliminatedGuards;
71 /// The set of guards which have been widened to include conditions to other
73 DenseSet<IntrinsicInst *> WidenedGuards;
75 /// Try to eliminate guard \p Guard by widening it into an earlier dominating
76 /// guard. \p DFSI is the DFS iterator on the dominator tree that is
77 /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
78 /// maps BasicBlocks to the set of guards seen in that block.
79 bool eliminateGuardViaWidening(
80 IntrinsicInst *Guard, const df_iterator<DomTreeNode *> &DFSI,
81 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
84 /// Used to keep track of which widening potential is more effective.
89 /// Widening is performance neutral as far as the cycles spent in check
90 /// conditions goes (but can still help, e.g., code layout, having less
94 /// Widening is profitable.
97 /// Widening is very profitable. Not significantly different from \c
98 /// WS_Positive, except by the order.
102 static StringRef scoreTypeToString(WideningScore WS);
104 /// Compute the score for widening the condition in \p DominatedGuard
105 /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
106 /// \p DominatingGuardLoop).
107 WideningScore computeWideningScore(IntrinsicInst *DominatedGuard,
108 Loop *DominatedGuardLoop,
109 IntrinsicInst *DominatingGuard,
110 Loop *DominatingGuardLoop);
112 /// Helper to check if \p V can be hoisted to \p InsertPos.
113 bool isAvailableAt(Value *V, Instruction *InsertPos) {
114 SmallPtrSet<Instruction *, 8> Visited;
115 return isAvailableAt(V, InsertPos, Visited);
118 bool isAvailableAt(Value *V, Instruction *InsertPos,
119 SmallPtrSetImpl<Instruction *> &Visited);
121 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
122 /// isAvailableAt returned true.
123 void makeAvailableAt(Value *V, Instruction *InsertPos);
125 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
126 /// to generate an expression computing the logical AND of \p Cond0 and \p
127 /// Cond1. Return true if the expression computing the AND is only as
128 /// expensive as computing one of the two. If \p InsertPt is true then
129 /// actually generate the resulting expression, make it available at \p
130 /// InsertPt and return it in \p Result (else no change to the IR is made).
131 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
134 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
135 /// with the constraint that \c Length is not negative. \c CheckInst is the
136 /// pre-existing instruction in the IR that computes the result of this range
145 explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
147 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
149 void setBase(Value *NewBase) { Base = NewBase; }
150 void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
152 Value *getBase() const { return Base; }
153 ConstantInt *getOffset() const { return Offset; }
154 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
155 Value *getLength() const { return Length; };
156 ICmpInst *getCheckInst() const { return CheckInst; }
158 void print(raw_ostream &OS, bool PrintTypes = false) {
160 Base->printAsOperand(OS, PrintTypes);
162 Offset->printAsOperand(OS, PrintTypes);
164 Length->printAsOperand(OS, PrintTypes);
167 LLVM_DUMP_METHOD void dump() {
173 /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
174 /// append them to \p Checks. Returns true on success, may clobber \c Checks
176 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
177 SmallPtrSet<Value *, 8> Visited;
178 return parseRangeChecks(CheckCond, Checks, Visited);
181 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
182 SmallPtrSetImpl<Value *> &Visited);
184 /// Combine the checks in \p Checks into a smaller set of checks and append
185 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
186 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
187 /// and \p CombinedChecks on success and on failure.
188 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
189 SmallVectorImpl<RangeCheck> &CombinedChecks);
191 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
192 /// computing only one of the two expressions?
193 bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
195 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
198 /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
199 /// whatever it is already checking).
200 void widenGuard(IntrinsicInst *ToWiden, Value *NewCondition) {
202 widenCondCommon(ToWiden->getArgOperand(0), NewCondition, ToWiden, Result);
203 ToWiden->setArgOperand(0, Result);
207 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree &PDT,
209 : DT(DT), PDT(PDT), LI(LI) {}
211 /// The entry point for this pass.
215 struct GuardWideningLegacyPass : public FunctionPass {
217 GuardWideningPass Impl;
219 GuardWideningLegacyPass() : FunctionPass(ID) {
220 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
223 bool runOnFunction(Function &F) override {
226 return GuardWideningImpl(
227 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
228 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(),
229 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()).run();
232 void getAnalysisUsage(AnalysisUsage &AU) const override {
233 AU.setPreservesCFG();
234 AU.addRequired<DominatorTreeWrapperPass>();
235 AU.addRequired<PostDominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
242 bool GuardWideningImpl::run() {
243 using namespace llvm::PatternMatch;
245 DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> GuardsInBlock;
246 bool Changed = false;
248 for (auto DFI = df_begin(DT.getRootNode()), DFE = df_end(DT.getRootNode());
250 auto *BB = (*DFI)->getBlock();
251 auto &CurrentList = GuardsInBlock[BB];
254 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
255 CurrentList.push_back(cast<IntrinsicInst>(&I));
257 for (auto *II : CurrentList)
258 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
261 for (auto *II : EliminatedGuards)
262 if (!WidenedGuards.count(II))
263 II->eraseFromParent();
268 bool GuardWideningImpl::eliminateGuardViaWidening(
269 IntrinsicInst *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
270 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
272 IntrinsicInst *BestSoFar = nullptr;
273 auto BestScoreSoFar = WS_IllegalOrNegative;
274 auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
276 // In the set of dominating guards, find the one we can merge GuardInst with
277 // for the most profit.
278 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
279 auto *CurBB = DFSI.getPath(i)->getBlock();
280 auto *CurLoop = LI.getLoopFor(CurBB);
281 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
282 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
284 auto I = GuardsInCurBB.begin();
285 auto E = GuardsInCurBB.end();
290 for (auto &I : *CurBB) {
291 if (Index == GuardsInCurBB.size())
293 if (GuardsInCurBB[Index] == &I)
296 assert(Index == GuardsInCurBB.size() &&
297 "Guards expected to be in order!");
301 assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
304 // Corner case: make sure we're only looking at guards strictly dominating
305 // GuardInst when visiting GuardInst->getParent().
306 auto NewEnd = std::find(I, E, GuardInst);
307 assert(NewEnd != E && "GuardInst not in its own block?");
311 for (auto *Candidate : make_range(I, E)) {
313 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
314 DEBUG(dbgs() << "Score between " << *GuardInst->getArgOperand(0)
315 << " and " << *Candidate->getArgOperand(0) << " is "
316 << scoreTypeToString(Score) << "\n");
317 if (Score > BestScoreSoFar) {
318 BestScoreSoFar = Score;
319 BestSoFar = Candidate;
324 if (BestScoreSoFar == WS_IllegalOrNegative) {
325 DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
329 assert(BestSoFar != GuardInst && "Should have never visited same guard!");
330 assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
332 DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
333 << " with score " << scoreTypeToString(BestScoreSoFar) << "\n");
334 widenGuard(BestSoFar, GuardInst->getArgOperand(0));
335 GuardInst->setArgOperand(0, ConstantInt::getTrue(GuardInst->getContext()));
336 EliminatedGuards.push_back(GuardInst);
337 WidenedGuards.insert(BestSoFar);
341 GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
342 IntrinsicInst *DominatedGuard, Loop *DominatedGuardLoop,
343 IntrinsicInst *DominatingGuard, Loop *DominatingGuardLoop) {
344 bool HoistingOutOfLoop = false;
346 if (DominatingGuardLoop != DominatedGuardLoop) {
347 if (DominatingGuardLoop &&
348 !DominatingGuardLoop->contains(DominatedGuardLoop))
349 return WS_IllegalOrNegative;
351 HoistingOutOfLoop = true;
354 if (!isAvailableAt(DominatedGuard->getArgOperand(0), DominatingGuard))
355 return WS_IllegalOrNegative;
357 bool HoistingOutOfIf =
358 !PDT.dominates(DominatedGuard->getParent(), DominatingGuard->getParent());
360 if (isWideningCondProfitable(DominatedGuard->getArgOperand(0),
361 DominatingGuard->getArgOperand(0)))
362 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
364 if (HoistingOutOfLoop)
367 return HoistingOutOfIf ? WS_IllegalOrNegative : WS_Neutral;
370 bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
371 SmallPtrSetImpl<Instruction *> &Visited) {
372 auto *Inst = dyn_cast<Instruction>(V);
373 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
376 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
377 Inst->mayReadFromMemory())
380 Visited.insert(Inst);
382 // We only want to go _up_ the dominance chain when recursing.
383 assert(!isa<PHINode>(Loc) &&
384 "PHIs should return false for isSafeToSpeculativelyExecute");
385 assert(DT.isReachableFromEntry(Inst->getParent()) &&
386 "We did a DFS from the block entry!");
387 return all_of(Inst->operands(),
388 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
391 void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
392 auto *Inst = dyn_cast<Instruction>(V);
393 if (!Inst || DT.dominates(Inst, Loc))
396 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
397 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
399 for (Value *Op : Inst->operands())
400 makeAvailableAt(Op, Loc);
402 Inst->moveBefore(Loc);
405 bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
406 Instruction *InsertPt, Value *&Result) {
407 using namespace llvm::PatternMatch;
410 // L >u C0 && L >u C1 -> L >u max(C0, C1)
411 ConstantInt *RHS0, *RHS1;
413 ICmpInst::Predicate Pred0, Pred1;
414 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
415 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
418 ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
420 ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
422 // SubsetIntersect is a subset of the actual mathematical intersection of
423 // CR0 and CR1, while SupersetIntersect is a superset of the actual
424 // mathematical intersection. If these two ConstantRanges are equal, then
425 // we know we were able to represent the actual mathematical intersection
426 // of CR0 and CR1, and can use the same to generate an icmp instruction.
428 // Given what we're doing here and the semantics of guards, it would
429 // actually be correct to just use SubsetIntersect, but that may be too
430 // aggressive in cases we care about.
431 auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
432 auto SupersetIntersect = CR0.intersectWith(CR1);
435 CmpInst::Predicate Pred;
436 if (SubsetIntersect == SupersetIntersect &&
437 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
439 ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
440 Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
448 SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
449 if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
450 combineRangeChecks(Checks, CombinedChecks)) {
453 for (auto &RC : CombinedChecks) {
454 makeAvailableAt(RC.getCheckInst(), InsertPt);
456 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
459 Result = RC.getCheckInst();
462 Result->setName("wide.chk");
468 // Base case -- just logical-and the two conditions together.
471 makeAvailableAt(Cond0, InsertPt);
472 makeAvailableAt(Cond1, InsertPt);
474 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
477 // We were not able to compute Cond0 AND Cond1 for the price of one.
481 bool GuardWideningImpl::parseRangeChecks(
482 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
483 SmallPtrSetImpl<Value *> &Visited) {
484 if (!Visited.insert(CheckCond).second)
487 using namespace llvm::PatternMatch;
490 Value *AndLHS, *AndRHS;
491 if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
492 return parseRangeChecks(AndLHS, Checks) &&
493 parseRangeChecks(AndRHS, Checks);
496 auto *IC = dyn_cast<ICmpInst>(CheckCond);
497 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
498 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
499 IC->getPredicate() != ICmpInst::ICMP_UGT))
502 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
503 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
504 std::swap(CmpLHS, CmpRHS);
506 auto &DL = IC->getModule()->getDataLayout();
508 GuardWideningImpl::RangeCheck Check(
509 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
512 if (!isKnownNonNegative(Check.getLength(), DL))
515 // What we have in \c Check now is a correct interpretation of \p CheckCond.
516 // Try to see if we can move some constant offsets into the \c Offset field.
519 auto &Ctx = CheckCond->getContext();
527 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
528 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
529 "Unreachable instruction?");
532 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
533 Check.setBase(OpLHS);
534 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
535 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
537 } else if (match(Check.getBase(),
538 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
539 unsigned BitWidth = OpLHS->getType()->getScalarSizeInBits();
540 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
541 computeKnownBits(OpLHS, KnownZero, KnownOne, DL);
542 if ((OpRHS->getValue() & KnownZero) == OpRHS->getValue()) {
543 Check.setBase(OpLHS);
544 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
545 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
551 Checks.push_back(Check);
555 bool GuardWideningImpl::combineRangeChecks(
556 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
557 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
558 unsigned OldCount = Checks.size();
559 while (!Checks.empty()) {
560 // Pick all of the range checks with a specific base and length, and try to
562 Value *CurrentBase = Checks.front().getBase();
563 Value *CurrentLength = Checks.front().getLength();
565 SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
567 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
568 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
571 std::copy_if(Checks.begin(), Checks.end(),
572 std::back_inserter(CurrentChecks), IsCurrentCheck);
573 Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
575 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
577 if (CurrentChecks.size() < 3) {
578 RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
579 CurrentChecks.end());
583 // CurrentChecks.size() will typically be 3 here, but so far there has been
584 // no need to hard-code that fact.
586 std::sort(CurrentChecks.begin(), CurrentChecks.end(),
587 [&](const GuardWideningImpl::RangeCheck &LHS,
588 const GuardWideningImpl::RangeCheck &RHS) {
589 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
592 // Note: std::sort should not invalidate the ChecksStart iterator.
594 ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
595 *MaxOffset = CurrentChecks.back().getOffset();
597 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
598 if ((MaxOffset->getValue() - MinOffset->getValue())
599 .ugt(APInt::getSignedMinValue(BitWidth)))
602 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
603 const APInt &HighOffset = MaxOffset->getValue();
604 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
605 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
608 if (MaxDiff.isMinValue() ||
609 !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
613 // We have a series of f+1 checks as:
615 // I+k_0 u< L ... Chk_0
616 // I_k_1 u< L ... Chk_1
618 // I_k_f u< L ... Chk_(f+1)
620 // with forall i in [0,f): k_f-k_i u< k_f-k_0 ... Precond_0
621 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
622 // k_f != k_0 ... Precond_2
625 // Chk_0 AND Chk_(f+1) implies all the other checks
627 // Informal proof sketch:
629 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
630 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
631 // thus I+k_f is the greatest unsigned value in that range.
633 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
634 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
635 // lie in [I+k_0,I+k_f], this proving our claim.
637 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
638 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
639 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
640 // range by definition, and the latter case is impossible:
642 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
643 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
645 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
646 // with 'x' above) to be at least >u INT_MIN.
648 RangeChecksOut.emplace_back(CurrentChecks.front());
649 RangeChecksOut.emplace_back(CurrentChecks.back());
652 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
653 return RangeChecksOut.size() != OldCount;
656 PreservedAnalyses GuardWideningPass::run(Function &F,
657 FunctionAnalysisManager &AM) {
658 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
659 auto &LI = AM.getResult<LoopAnalysis>(F);
660 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
661 bool Changed = GuardWideningImpl(DT, PDT, LI).run();
662 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
665 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
667 case WS_IllegalOrNegative:
668 return "IllegalOrNegative";
673 case WS_VeryPositive:
674 return "VeryPositive";
677 llvm_unreachable("Fully covered switch above!");
680 char GuardWideningLegacyPass::ID = 0;
682 INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
684 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
685 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
686 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
687 INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
690 FunctionPass *llvm::createGuardWideningPass() {
691 return new GuardWideningLegacyPass();