xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/GuardWidening.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the guard widening pass.  The semantics of the
11*9880d681SAndroid Build Coastguard Worker // @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
12*9880d681SAndroid Build Coastguard Worker // more often that it did before the transform.  This optimization is called
13*9880d681SAndroid Build Coastguard Worker // "widening" and can be used hoist and common runtime checks in situations like
14*9880d681SAndroid Build Coastguard Worker // these:
15*9880d681SAndroid Build Coastguard Worker //
16*9880d681SAndroid Build Coastguard Worker //    %cmp0 = 7 u< Length
17*9880d681SAndroid Build Coastguard Worker //    call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
18*9880d681SAndroid Build Coastguard Worker //    call @unknown_side_effects()
19*9880d681SAndroid Build Coastguard Worker //    %cmp1 = 9 u< Length
20*9880d681SAndroid Build Coastguard Worker //    call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
21*9880d681SAndroid Build Coastguard Worker //    ...
22*9880d681SAndroid Build Coastguard Worker //
23*9880d681SAndroid Build Coastguard Worker // =>
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker //    %cmp0 = 9 u< Length
26*9880d681SAndroid Build Coastguard Worker //    call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
27*9880d681SAndroid Build Coastguard Worker //    call @unknown_side_effects()
28*9880d681SAndroid Build Coastguard Worker //    ...
29*9880d681SAndroid Build Coastguard Worker //
30*9880d681SAndroid Build Coastguard Worker // If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
31*9880d681SAndroid Build Coastguard Worker // generic implementation of the same function, which will have the correct
32*9880d681SAndroid Build Coastguard Worker // semantics from that point onward.  It is always _legal_ to deoptimize (so
33*9880d681SAndroid Build Coastguard Worker // replacing %cmp0 with false is "correct"), though it may not always be
34*9880d681SAndroid Build Coastguard Worker // profitable to do so.
35*9880d681SAndroid Build Coastguard Worker //
36*9880d681SAndroid Build Coastguard Worker // NB! This pass is a work in progress.  It hasn't been tuned to be "production
37*9880d681SAndroid Build Coastguard Worker // ready" yet.  It is known to have quadriatic running time and will not scale
38*9880d681SAndroid Build Coastguard Worker // to large numbers of guards
39*9880d681SAndroid Build Coastguard Worker //
40*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
41*9880d681SAndroid Build Coastguard Worker 
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/GuardWidening.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DepthFirstIterator.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/PostDominators.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
54*9880d681SAndroid Build Coastguard Worker 
55*9880d681SAndroid Build Coastguard Worker using namespace llvm;
56*9880d681SAndroid Build Coastguard Worker 
57*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "guard-widening"
58*9880d681SAndroid Build Coastguard Worker 
59*9880d681SAndroid Build Coastguard Worker namespace {
60*9880d681SAndroid Build Coastguard Worker 
61*9880d681SAndroid Build Coastguard Worker class GuardWideningImpl {
62*9880d681SAndroid Build Coastguard Worker   DominatorTree &DT;
63*9880d681SAndroid Build Coastguard Worker   PostDominatorTree &PDT;
64*9880d681SAndroid Build Coastguard Worker   LoopInfo &LI;
65*9880d681SAndroid Build Coastguard Worker 
66*9880d681SAndroid Build Coastguard Worker   /// The set of guards whose conditions have been widened into dominating
67*9880d681SAndroid Build Coastguard Worker   /// guards.
68*9880d681SAndroid Build Coastguard Worker   SmallVector<IntrinsicInst *, 16> EliminatedGuards;
69*9880d681SAndroid Build Coastguard Worker 
70*9880d681SAndroid Build Coastguard Worker   /// The set of guards which have been widened to include conditions to other
71*9880d681SAndroid Build Coastguard Worker   /// guards.
72*9880d681SAndroid Build Coastguard Worker   DenseSet<IntrinsicInst *> WidenedGuards;
73*9880d681SAndroid Build Coastguard Worker 
74*9880d681SAndroid Build Coastguard Worker   /// Try to eliminate guard \p Guard by widening it into an earlier dominating
75*9880d681SAndroid Build Coastguard Worker   /// guard.  \p DFSI is the DFS iterator on the dominator tree that is
76*9880d681SAndroid Build Coastguard Worker   /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
77*9880d681SAndroid Build Coastguard Worker   /// maps BasicBlocks to the set of guards seen in that block.
78*9880d681SAndroid Build Coastguard Worker   bool eliminateGuardViaWidening(
79*9880d681SAndroid Build Coastguard Worker       IntrinsicInst *Guard, const df_iterator<DomTreeNode *> &DFSI,
80*9880d681SAndroid Build Coastguard Worker       const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
81*9880d681SAndroid Build Coastguard Worker           GuardsPerBlock);
82*9880d681SAndroid Build Coastguard Worker 
83*9880d681SAndroid Build Coastguard Worker   /// Used to keep track of which widening potential is more effective.
84*9880d681SAndroid Build Coastguard Worker   enum WideningScore {
85*9880d681SAndroid Build Coastguard Worker     /// Don't widen.
86*9880d681SAndroid Build Coastguard Worker     WS_IllegalOrNegative,
87*9880d681SAndroid Build Coastguard Worker 
88*9880d681SAndroid Build Coastguard Worker     /// Widening is performance neutral as far as the cycles spent in check
89*9880d681SAndroid Build Coastguard Worker     /// conditions goes (but can still help, e.g., code layout, having less
90*9880d681SAndroid Build Coastguard Worker     /// deopt state).
91*9880d681SAndroid Build Coastguard Worker     WS_Neutral,
92*9880d681SAndroid Build Coastguard Worker 
93*9880d681SAndroid Build Coastguard Worker     /// Widening is profitable.
94*9880d681SAndroid Build Coastguard Worker     WS_Positive,
95*9880d681SAndroid Build Coastguard Worker 
96*9880d681SAndroid Build Coastguard Worker     /// Widening is very profitable.  Not significantly different from \c
97*9880d681SAndroid Build Coastguard Worker     /// WS_Positive, except by the order.
98*9880d681SAndroid Build Coastguard Worker     WS_VeryPositive
99*9880d681SAndroid Build Coastguard Worker   };
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker   static StringRef scoreTypeToString(WideningScore WS);
102*9880d681SAndroid Build Coastguard Worker 
103*9880d681SAndroid Build Coastguard Worker   /// Compute the score for widening the condition in \p DominatedGuard
104*9880d681SAndroid Build Coastguard Worker   /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
105*9880d681SAndroid Build Coastguard Worker   /// \p DominatingGuardLoop).
106*9880d681SAndroid Build Coastguard Worker   WideningScore computeWideningScore(IntrinsicInst *DominatedGuard,
107*9880d681SAndroid Build Coastguard Worker                                      Loop *DominatedGuardLoop,
108*9880d681SAndroid Build Coastguard Worker                                      IntrinsicInst *DominatingGuard,
109*9880d681SAndroid Build Coastguard Worker                                      Loop *DominatingGuardLoop);
110*9880d681SAndroid Build Coastguard Worker 
111*9880d681SAndroid Build Coastguard Worker   /// Helper to check if \p V can be hoisted to \p InsertPos.
isAvailableAt(Value * V,Instruction * InsertPos)112*9880d681SAndroid Build Coastguard Worker   bool isAvailableAt(Value *V, Instruction *InsertPos) {
113*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<Instruction *, 8> Visited;
114*9880d681SAndroid Build Coastguard Worker     return isAvailableAt(V, InsertPos, Visited);
115*9880d681SAndroid Build Coastguard Worker   }
116*9880d681SAndroid Build Coastguard Worker 
117*9880d681SAndroid Build Coastguard Worker   bool isAvailableAt(Value *V, Instruction *InsertPos,
118*9880d681SAndroid Build Coastguard Worker                      SmallPtrSetImpl<Instruction *> &Visited);
119*9880d681SAndroid Build Coastguard Worker 
120*9880d681SAndroid Build Coastguard Worker   /// Helper to hoist \p V to \p InsertPos.  Guaranteed to succeed if \c
121*9880d681SAndroid Build Coastguard Worker   /// isAvailableAt returned true.
122*9880d681SAndroid Build Coastguard Worker   void makeAvailableAt(Value *V, Instruction *InsertPos);
123*9880d681SAndroid Build Coastguard Worker 
124*9880d681SAndroid Build Coastguard Worker   /// Common helper used by \c widenGuard and \c isWideningCondProfitable.  Try
125*9880d681SAndroid Build Coastguard Worker   /// to generate an expression computing the logical AND of \p Cond0 and \p
126*9880d681SAndroid Build Coastguard Worker   /// Cond1.  Return true if the expression computing the AND is only as
127*9880d681SAndroid Build Coastguard Worker   /// expensive as computing one of the two. If \p InsertPt is true then
128*9880d681SAndroid Build Coastguard Worker   /// actually generate the resulting expression, make it available at \p
129*9880d681SAndroid Build Coastguard Worker   /// InsertPt and return it in \p Result (else no change to the IR is made).
130*9880d681SAndroid Build Coastguard Worker   bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
131*9880d681SAndroid Build Coastguard Worker                        Value *&Result);
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker   /// Represents a range check of the form \c Base + \c Offset u< \c Length,
134*9880d681SAndroid Build Coastguard Worker   /// with the constraint that \c Length is not negative.  \c CheckInst is the
135*9880d681SAndroid Build Coastguard Worker   /// pre-existing instruction in the IR that computes the result of this range
136*9880d681SAndroid Build Coastguard Worker   /// check.
137*9880d681SAndroid Build Coastguard Worker   class RangeCheck {
138*9880d681SAndroid Build Coastguard Worker     Value *Base;
139*9880d681SAndroid Build Coastguard Worker     ConstantInt *Offset;
140*9880d681SAndroid Build Coastguard Worker     Value *Length;
141*9880d681SAndroid Build Coastguard Worker     ICmpInst *CheckInst;
142*9880d681SAndroid Build Coastguard Worker 
143*9880d681SAndroid Build Coastguard Worker   public:
RangeCheck(Value * Base,ConstantInt * Offset,Value * Length,ICmpInst * CheckInst)144*9880d681SAndroid Build Coastguard Worker     explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
145*9880d681SAndroid Build Coastguard Worker                         ICmpInst *CheckInst)
146*9880d681SAndroid Build Coastguard Worker         : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
147*9880d681SAndroid Build Coastguard Worker 
setBase(Value * NewBase)148*9880d681SAndroid Build Coastguard Worker     void setBase(Value *NewBase) { Base = NewBase; }
setOffset(ConstantInt * NewOffset)149*9880d681SAndroid Build Coastguard Worker     void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
150*9880d681SAndroid Build Coastguard Worker 
getBase() const151*9880d681SAndroid Build Coastguard Worker     Value *getBase() const { return Base; }
getOffset() const152*9880d681SAndroid Build Coastguard Worker     ConstantInt *getOffset() const { return Offset; }
getOffsetValue() const153*9880d681SAndroid Build Coastguard Worker     const APInt &getOffsetValue() const { return getOffset()->getValue(); }
getLength() const154*9880d681SAndroid Build Coastguard Worker     Value *getLength() const { return Length; };
getCheckInst() const155*9880d681SAndroid Build Coastguard Worker     ICmpInst *getCheckInst() const { return CheckInst; }
156*9880d681SAndroid Build Coastguard Worker 
print(raw_ostream & OS,bool PrintTypes=false)157*9880d681SAndroid Build Coastguard Worker     void print(raw_ostream &OS, bool PrintTypes = false) {
158*9880d681SAndroid Build Coastguard Worker       OS << "Base: ";
159*9880d681SAndroid Build Coastguard Worker       Base->printAsOperand(OS, PrintTypes);
160*9880d681SAndroid Build Coastguard Worker       OS << " Offset: ";
161*9880d681SAndroid Build Coastguard Worker       Offset->printAsOperand(OS, PrintTypes);
162*9880d681SAndroid Build Coastguard Worker       OS << " Length: ";
163*9880d681SAndroid Build Coastguard Worker       Length->printAsOperand(OS, PrintTypes);
164*9880d681SAndroid Build Coastguard Worker     }
165*9880d681SAndroid Build Coastguard Worker 
dump()166*9880d681SAndroid Build Coastguard Worker     LLVM_DUMP_METHOD void dump() {
167*9880d681SAndroid Build Coastguard Worker       print(dbgs());
168*9880d681SAndroid Build Coastguard Worker       dbgs() << "\n";
169*9880d681SAndroid Build Coastguard Worker     }
170*9880d681SAndroid Build Coastguard Worker   };
171*9880d681SAndroid Build Coastguard Worker 
172*9880d681SAndroid Build Coastguard Worker   /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
173*9880d681SAndroid Build Coastguard Worker   /// append them to \p Checks.  Returns true on success, may clobber \c Checks
174*9880d681SAndroid Build Coastguard Worker   /// on failure.
parseRangeChecks(Value * CheckCond,SmallVectorImpl<RangeCheck> & Checks)175*9880d681SAndroid Build Coastguard Worker   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
176*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<Value *, 8> Visited;
177*9880d681SAndroid Build Coastguard Worker     return parseRangeChecks(CheckCond, Checks, Visited);
178*9880d681SAndroid Build Coastguard Worker   }
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
181*9880d681SAndroid Build Coastguard Worker                         SmallPtrSetImpl<Value *> &Visited);
182*9880d681SAndroid Build Coastguard Worker 
183*9880d681SAndroid Build Coastguard Worker   /// Combine the checks in \p Checks into a smaller set of checks and append
184*9880d681SAndroid Build Coastguard Worker   /// them into \p CombinedChecks.  Return true on success (i.e. all of checks
185*9880d681SAndroid Build Coastguard Worker   /// in \p Checks were combined into \p CombinedChecks).  Clobbers \p Checks
186*9880d681SAndroid Build Coastguard Worker   /// and \p CombinedChecks on success and on failure.
187*9880d681SAndroid Build Coastguard Worker   bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
188*9880d681SAndroid Build Coastguard Worker                           SmallVectorImpl<RangeCheck> &CombinedChecks);
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker   /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
191*9880d681SAndroid Build Coastguard Worker   /// computing only one of the two expressions?
isWideningCondProfitable(Value * Cond0,Value * Cond1)192*9880d681SAndroid Build Coastguard Worker   bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
193*9880d681SAndroid Build Coastguard Worker     Value *ResultUnused;
194*9880d681SAndroid Build Coastguard Worker     return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
195*9880d681SAndroid Build Coastguard Worker   }
196*9880d681SAndroid Build Coastguard Worker 
197*9880d681SAndroid Build Coastguard Worker   /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
198*9880d681SAndroid Build Coastguard Worker   /// whatever it is already checking).
widenGuard(IntrinsicInst * ToWiden,Value * NewCondition)199*9880d681SAndroid Build Coastguard Worker   void widenGuard(IntrinsicInst *ToWiden, Value *NewCondition) {
200*9880d681SAndroid Build Coastguard Worker     Value *Result;
201*9880d681SAndroid Build Coastguard Worker     widenCondCommon(ToWiden->getArgOperand(0), NewCondition, ToWiden, Result);
202*9880d681SAndroid Build Coastguard Worker     ToWiden->setArgOperand(0, Result);
203*9880d681SAndroid Build Coastguard Worker   }
204*9880d681SAndroid Build Coastguard Worker 
205*9880d681SAndroid Build Coastguard Worker public:
GuardWideningImpl(DominatorTree & DT,PostDominatorTree & PDT,LoopInfo & LI)206*9880d681SAndroid Build Coastguard Worker   explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree &PDT,
207*9880d681SAndroid Build Coastguard Worker                              LoopInfo &LI)
208*9880d681SAndroid Build Coastguard Worker       : DT(DT), PDT(PDT), LI(LI) {}
209*9880d681SAndroid Build Coastguard Worker 
210*9880d681SAndroid Build Coastguard Worker   /// The entry point for this pass.
211*9880d681SAndroid Build Coastguard Worker   bool run();
212*9880d681SAndroid Build Coastguard Worker };
213*9880d681SAndroid Build Coastguard Worker 
214*9880d681SAndroid Build Coastguard Worker struct GuardWideningLegacyPass : public FunctionPass {
215*9880d681SAndroid Build Coastguard Worker   static char ID;
216*9880d681SAndroid Build Coastguard Worker   GuardWideningPass Impl;
217*9880d681SAndroid Build Coastguard Worker 
GuardWideningLegacyPass__anond39e36530111::GuardWideningLegacyPass218*9880d681SAndroid Build Coastguard Worker   GuardWideningLegacyPass() : FunctionPass(ID) {
219*9880d681SAndroid Build Coastguard Worker     initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
220*9880d681SAndroid Build Coastguard Worker   }
221*9880d681SAndroid Build Coastguard Worker 
runOnFunction__anond39e36530111::GuardWideningLegacyPass222*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F) override {
223*9880d681SAndroid Build Coastguard Worker     if (skipFunction(F))
224*9880d681SAndroid Build Coastguard Worker       return false;
225*9880d681SAndroid Build Coastguard Worker     return GuardWideningImpl(
226*9880d681SAndroid Build Coastguard Worker                getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
227*9880d681SAndroid Build Coastguard Worker                getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(),
228*9880d681SAndroid Build Coastguard Worker                getAnalysis<LoopInfoWrapperPass>().getLoopInfo()).run();
229*9880d681SAndroid Build Coastguard Worker   }
230*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage__anond39e36530111::GuardWideningLegacyPass231*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
232*9880d681SAndroid Build Coastguard Worker     AU.setPreservesCFG();
233*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
234*9880d681SAndroid Build Coastguard Worker     AU.addRequired<PostDominatorTreeWrapperPass>();
235*9880d681SAndroid Build Coastguard Worker     AU.addRequired<LoopInfoWrapperPass>();
236*9880d681SAndroid Build Coastguard Worker   }
237*9880d681SAndroid Build Coastguard Worker };
238*9880d681SAndroid Build Coastguard Worker 
239*9880d681SAndroid Build Coastguard Worker }
240*9880d681SAndroid Build Coastguard Worker 
run()241*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::run() {
242*9880d681SAndroid Build Coastguard Worker   using namespace llvm::PatternMatch;
243*9880d681SAndroid Build Coastguard Worker 
244*9880d681SAndroid Build Coastguard Worker   DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> GuardsInBlock;
245*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
246*9880d681SAndroid Build Coastguard Worker 
247*9880d681SAndroid Build Coastguard Worker   for (auto DFI = df_begin(DT.getRootNode()), DFE = df_end(DT.getRootNode());
248*9880d681SAndroid Build Coastguard Worker        DFI != DFE; ++DFI) {
249*9880d681SAndroid Build Coastguard Worker     auto *BB = (*DFI)->getBlock();
250*9880d681SAndroid Build Coastguard Worker     auto &CurrentList = GuardsInBlock[BB];
251*9880d681SAndroid Build Coastguard Worker 
252*9880d681SAndroid Build Coastguard Worker     for (auto &I : *BB)
253*9880d681SAndroid Build Coastguard Worker       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
254*9880d681SAndroid Build Coastguard Worker         CurrentList.push_back(cast<IntrinsicInst>(&I));
255*9880d681SAndroid Build Coastguard Worker 
256*9880d681SAndroid Build Coastguard Worker     for (auto *II : CurrentList)
257*9880d681SAndroid Build Coastguard Worker       Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
258*9880d681SAndroid Build Coastguard Worker   }
259*9880d681SAndroid Build Coastguard Worker 
260*9880d681SAndroid Build Coastguard Worker   for (auto *II : EliminatedGuards)
261*9880d681SAndroid Build Coastguard Worker     if (!WidenedGuards.count(II))
262*9880d681SAndroid Build Coastguard Worker       II->eraseFromParent();
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker   return Changed;
265*9880d681SAndroid Build Coastguard Worker }
266*9880d681SAndroid Build Coastguard Worker 
eliminateGuardViaWidening(IntrinsicInst * GuardInst,const df_iterator<DomTreeNode * > & DFSI,const DenseMap<BasicBlock *,SmallVector<IntrinsicInst *,8>> & GuardsInBlock)267*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::eliminateGuardViaWidening(
268*9880d681SAndroid Build Coastguard Worker     IntrinsicInst *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
269*9880d681SAndroid Build Coastguard Worker     const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
270*9880d681SAndroid Build Coastguard Worker         GuardsInBlock) {
271*9880d681SAndroid Build Coastguard Worker   IntrinsicInst *BestSoFar = nullptr;
272*9880d681SAndroid Build Coastguard Worker   auto BestScoreSoFar = WS_IllegalOrNegative;
273*9880d681SAndroid Build Coastguard Worker   auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker   // In the set of dominating guards, find the one we can merge GuardInst with
276*9880d681SAndroid Build Coastguard Worker   // for the most profit.
277*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
278*9880d681SAndroid Build Coastguard Worker     auto *CurBB = DFSI.getPath(i)->getBlock();
279*9880d681SAndroid Build Coastguard Worker     auto *CurLoop = LI.getLoopFor(CurBB);
280*9880d681SAndroid Build Coastguard Worker     assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
281*9880d681SAndroid Build Coastguard Worker     const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
282*9880d681SAndroid Build Coastguard Worker 
283*9880d681SAndroid Build Coastguard Worker     auto I = GuardsInCurBB.begin();
284*9880d681SAndroid Build Coastguard Worker     auto E = GuardsInCurBB.end();
285*9880d681SAndroid Build Coastguard Worker 
286*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
287*9880d681SAndroid Build Coastguard Worker     {
288*9880d681SAndroid Build Coastguard Worker       unsigned Index = 0;
289*9880d681SAndroid Build Coastguard Worker       for (auto &I : *CurBB) {
290*9880d681SAndroid Build Coastguard Worker         if (Index == GuardsInCurBB.size())
291*9880d681SAndroid Build Coastguard Worker           break;
292*9880d681SAndroid Build Coastguard Worker         if (GuardsInCurBB[Index] == &I)
293*9880d681SAndroid Build Coastguard Worker           Index++;
294*9880d681SAndroid Build Coastguard Worker       }
295*9880d681SAndroid Build Coastguard Worker       assert(Index == GuardsInCurBB.size() &&
296*9880d681SAndroid Build Coastguard Worker              "Guards expected to be in order!");
297*9880d681SAndroid Build Coastguard Worker     }
298*9880d681SAndroid Build Coastguard Worker #endif
299*9880d681SAndroid Build Coastguard Worker 
300*9880d681SAndroid Build Coastguard Worker     assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker     if (i == (e - 1)) {
303*9880d681SAndroid Build Coastguard Worker       // Corner case: make sure we're only looking at guards strictly dominating
304*9880d681SAndroid Build Coastguard Worker       // GuardInst when visiting GuardInst->getParent().
305*9880d681SAndroid Build Coastguard Worker       auto NewEnd = std::find(I, E, GuardInst);
306*9880d681SAndroid Build Coastguard Worker       assert(NewEnd != E && "GuardInst not in its own block?");
307*9880d681SAndroid Build Coastguard Worker       E = NewEnd;
308*9880d681SAndroid Build Coastguard Worker     }
309*9880d681SAndroid Build Coastguard Worker 
310*9880d681SAndroid Build Coastguard Worker     for (auto *Candidate : make_range(I, E)) {
311*9880d681SAndroid Build Coastguard Worker       auto Score =
312*9880d681SAndroid Build Coastguard Worker           computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
313*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "Score between " << *GuardInst->getArgOperand(0)
314*9880d681SAndroid Build Coastguard Worker                    << " and " << *Candidate->getArgOperand(0) << " is "
315*9880d681SAndroid Build Coastguard Worker                    << scoreTypeToString(Score) << "\n");
316*9880d681SAndroid Build Coastguard Worker       if (Score > BestScoreSoFar) {
317*9880d681SAndroid Build Coastguard Worker         BestScoreSoFar = Score;
318*9880d681SAndroid Build Coastguard Worker         BestSoFar = Candidate;
319*9880d681SAndroid Build Coastguard Worker       }
320*9880d681SAndroid Build Coastguard Worker     }
321*9880d681SAndroid Build Coastguard Worker   }
322*9880d681SAndroid Build Coastguard Worker 
323*9880d681SAndroid Build Coastguard Worker   if (BestScoreSoFar == WS_IllegalOrNegative) {
324*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
325*9880d681SAndroid Build Coastguard Worker     return false;
326*9880d681SAndroid Build Coastguard Worker   }
327*9880d681SAndroid Build Coastguard Worker 
328*9880d681SAndroid Build Coastguard Worker   assert(BestSoFar != GuardInst && "Should have never visited same guard!");
329*9880d681SAndroid Build Coastguard Worker   assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
330*9880d681SAndroid Build Coastguard Worker 
331*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
332*9880d681SAndroid Build Coastguard Worker                << " with score " << scoreTypeToString(BestScoreSoFar) << "\n");
333*9880d681SAndroid Build Coastguard Worker   widenGuard(BestSoFar, GuardInst->getArgOperand(0));
334*9880d681SAndroid Build Coastguard Worker   GuardInst->setArgOperand(0, ConstantInt::getTrue(GuardInst->getContext()));
335*9880d681SAndroid Build Coastguard Worker   EliminatedGuards.push_back(GuardInst);
336*9880d681SAndroid Build Coastguard Worker   WidenedGuards.insert(BestSoFar);
337*9880d681SAndroid Build Coastguard Worker   return true;
338*9880d681SAndroid Build Coastguard Worker }
339*9880d681SAndroid Build Coastguard Worker 
computeWideningScore(IntrinsicInst * DominatedGuard,Loop * DominatedGuardLoop,IntrinsicInst * DominatingGuard,Loop * DominatingGuardLoop)340*9880d681SAndroid Build Coastguard Worker GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
341*9880d681SAndroid Build Coastguard Worker     IntrinsicInst *DominatedGuard, Loop *DominatedGuardLoop,
342*9880d681SAndroid Build Coastguard Worker     IntrinsicInst *DominatingGuard, Loop *DominatingGuardLoop) {
343*9880d681SAndroid Build Coastguard Worker   bool HoistingOutOfLoop = false;
344*9880d681SAndroid Build Coastguard Worker 
345*9880d681SAndroid Build Coastguard Worker   if (DominatingGuardLoop != DominatedGuardLoop) {
346*9880d681SAndroid Build Coastguard Worker     if (DominatingGuardLoop &&
347*9880d681SAndroid Build Coastguard Worker         !DominatingGuardLoop->contains(DominatedGuardLoop))
348*9880d681SAndroid Build Coastguard Worker       return WS_IllegalOrNegative;
349*9880d681SAndroid Build Coastguard Worker 
350*9880d681SAndroid Build Coastguard Worker     HoistingOutOfLoop = true;
351*9880d681SAndroid Build Coastguard Worker   }
352*9880d681SAndroid Build Coastguard Worker 
353*9880d681SAndroid Build Coastguard Worker   if (!isAvailableAt(DominatedGuard->getArgOperand(0), DominatingGuard))
354*9880d681SAndroid Build Coastguard Worker     return WS_IllegalOrNegative;
355*9880d681SAndroid Build Coastguard Worker 
356*9880d681SAndroid Build Coastguard Worker   bool HoistingOutOfIf =
357*9880d681SAndroid Build Coastguard Worker       !PDT.dominates(DominatedGuard->getParent(), DominatingGuard->getParent());
358*9880d681SAndroid Build Coastguard Worker 
359*9880d681SAndroid Build Coastguard Worker   if (isWideningCondProfitable(DominatedGuard->getArgOperand(0),
360*9880d681SAndroid Build Coastguard Worker                                DominatingGuard->getArgOperand(0)))
361*9880d681SAndroid Build Coastguard Worker     return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   if (HoistingOutOfLoop)
364*9880d681SAndroid Build Coastguard Worker     return WS_Positive;
365*9880d681SAndroid Build Coastguard Worker 
366*9880d681SAndroid Build Coastguard Worker   return HoistingOutOfIf ? WS_IllegalOrNegative : WS_Neutral;
367*9880d681SAndroid Build Coastguard Worker }
368*9880d681SAndroid Build Coastguard Worker 
isAvailableAt(Value * V,Instruction * Loc,SmallPtrSetImpl<Instruction * > & Visited)369*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
370*9880d681SAndroid Build Coastguard Worker                                       SmallPtrSetImpl<Instruction *> &Visited) {
371*9880d681SAndroid Build Coastguard Worker   auto *Inst = dyn_cast<Instruction>(V);
372*9880d681SAndroid Build Coastguard Worker   if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
373*9880d681SAndroid Build Coastguard Worker     return true;
374*9880d681SAndroid Build Coastguard Worker 
375*9880d681SAndroid Build Coastguard Worker   if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
376*9880d681SAndroid Build Coastguard Worker       Inst->mayReadFromMemory())
377*9880d681SAndroid Build Coastguard Worker     return false;
378*9880d681SAndroid Build Coastguard Worker 
379*9880d681SAndroid Build Coastguard Worker   Visited.insert(Inst);
380*9880d681SAndroid Build Coastguard Worker 
381*9880d681SAndroid Build Coastguard Worker   // We only want to go _up_ the dominance chain when recursing.
382*9880d681SAndroid Build Coastguard Worker   assert(!isa<PHINode>(Loc) &&
383*9880d681SAndroid Build Coastguard Worker          "PHIs should return false for isSafeToSpeculativelyExecute");
384*9880d681SAndroid Build Coastguard Worker   assert(DT.isReachableFromEntry(Inst->getParent()) &&
385*9880d681SAndroid Build Coastguard Worker          "We did a DFS from the block entry!");
386*9880d681SAndroid Build Coastguard Worker   return all_of(Inst->operands(),
387*9880d681SAndroid Build Coastguard Worker                 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
388*9880d681SAndroid Build Coastguard Worker }
389*9880d681SAndroid Build Coastguard Worker 
makeAvailableAt(Value * V,Instruction * Loc)390*9880d681SAndroid Build Coastguard Worker void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
391*9880d681SAndroid Build Coastguard Worker   auto *Inst = dyn_cast<Instruction>(V);
392*9880d681SAndroid Build Coastguard Worker   if (!Inst || DT.dominates(Inst, Loc))
393*9880d681SAndroid Build Coastguard Worker     return;
394*9880d681SAndroid Build Coastguard Worker 
395*9880d681SAndroid Build Coastguard Worker   assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
396*9880d681SAndroid Build Coastguard Worker          !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
397*9880d681SAndroid Build Coastguard Worker 
398*9880d681SAndroid Build Coastguard Worker   for (Value *Op : Inst->operands())
399*9880d681SAndroid Build Coastguard Worker     makeAvailableAt(Op, Loc);
400*9880d681SAndroid Build Coastguard Worker 
401*9880d681SAndroid Build Coastguard Worker   Inst->moveBefore(Loc);
402*9880d681SAndroid Build Coastguard Worker }
403*9880d681SAndroid Build Coastguard Worker 
widenCondCommon(Value * Cond0,Value * Cond1,Instruction * InsertPt,Value * & Result)404*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
405*9880d681SAndroid Build Coastguard Worker                                         Instruction *InsertPt, Value *&Result) {
406*9880d681SAndroid Build Coastguard Worker   using namespace llvm::PatternMatch;
407*9880d681SAndroid Build Coastguard Worker 
408*9880d681SAndroid Build Coastguard Worker   {
409*9880d681SAndroid Build Coastguard Worker     // L >u C0 && L >u C1  ->  L >u max(C0, C1)
410*9880d681SAndroid Build Coastguard Worker     ConstantInt *RHS0, *RHS1;
411*9880d681SAndroid Build Coastguard Worker     Value *LHS;
412*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate Pred0, Pred1;
413*9880d681SAndroid Build Coastguard Worker     if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
414*9880d681SAndroid Build Coastguard Worker         match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
415*9880d681SAndroid Build Coastguard Worker 
416*9880d681SAndroid Build Coastguard Worker       ConstantRange CR0 =
417*9880d681SAndroid Build Coastguard Worker           ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
418*9880d681SAndroid Build Coastguard Worker       ConstantRange CR1 =
419*9880d681SAndroid Build Coastguard Worker           ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
420*9880d681SAndroid Build Coastguard Worker 
421*9880d681SAndroid Build Coastguard Worker       // SubsetIntersect is a subset of the actual mathematical intersection of
422*9880d681SAndroid Build Coastguard Worker       // CR0 and CR1, while SupersetIntersect is a superset of the actual
423*9880d681SAndroid Build Coastguard Worker       // mathematical intersection.  If these two ConstantRanges are equal, then
424*9880d681SAndroid Build Coastguard Worker       // we know we were able to represent the actual mathematical intersection
425*9880d681SAndroid Build Coastguard Worker       // of CR0 and CR1, and can use the same to generate an icmp instruction.
426*9880d681SAndroid Build Coastguard Worker       //
427*9880d681SAndroid Build Coastguard Worker       // Given what we're doing here and the semantics of guards, it would
428*9880d681SAndroid Build Coastguard Worker       // actually be correct to just use SubsetIntersect, but that may be too
429*9880d681SAndroid Build Coastguard Worker       // aggressive in cases we care about.
430*9880d681SAndroid Build Coastguard Worker       auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
431*9880d681SAndroid Build Coastguard Worker       auto SupersetIntersect = CR0.intersectWith(CR1);
432*9880d681SAndroid Build Coastguard Worker 
433*9880d681SAndroid Build Coastguard Worker       APInt NewRHSAP;
434*9880d681SAndroid Build Coastguard Worker       CmpInst::Predicate Pred;
435*9880d681SAndroid Build Coastguard Worker       if (SubsetIntersect == SupersetIntersect &&
436*9880d681SAndroid Build Coastguard Worker           SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
437*9880d681SAndroid Build Coastguard Worker         if (InsertPt) {
438*9880d681SAndroid Build Coastguard Worker           ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
439*9880d681SAndroid Build Coastguard Worker           Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
440*9880d681SAndroid Build Coastguard Worker         }
441*9880d681SAndroid Build Coastguard Worker         return true;
442*9880d681SAndroid Build Coastguard Worker       }
443*9880d681SAndroid Build Coastguard Worker     }
444*9880d681SAndroid Build Coastguard Worker   }
445*9880d681SAndroid Build Coastguard Worker 
446*9880d681SAndroid Build Coastguard Worker   {
447*9880d681SAndroid Build Coastguard Worker     SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
448*9880d681SAndroid Build Coastguard Worker     if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
449*9880d681SAndroid Build Coastguard Worker         combineRangeChecks(Checks, CombinedChecks)) {
450*9880d681SAndroid Build Coastguard Worker       if (InsertPt) {
451*9880d681SAndroid Build Coastguard Worker         Result = nullptr;
452*9880d681SAndroid Build Coastguard Worker         for (auto &RC : CombinedChecks) {
453*9880d681SAndroid Build Coastguard Worker           makeAvailableAt(RC.getCheckInst(), InsertPt);
454*9880d681SAndroid Build Coastguard Worker           if (Result)
455*9880d681SAndroid Build Coastguard Worker             Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
456*9880d681SAndroid Build Coastguard Worker                                                InsertPt);
457*9880d681SAndroid Build Coastguard Worker           else
458*9880d681SAndroid Build Coastguard Worker             Result = RC.getCheckInst();
459*9880d681SAndroid Build Coastguard Worker         }
460*9880d681SAndroid Build Coastguard Worker 
461*9880d681SAndroid Build Coastguard Worker         Result->setName("wide.chk");
462*9880d681SAndroid Build Coastguard Worker       }
463*9880d681SAndroid Build Coastguard Worker       return true;
464*9880d681SAndroid Build Coastguard Worker     }
465*9880d681SAndroid Build Coastguard Worker   }
466*9880d681SAndroid Build Coastguard Worker 
467*9880d681SAndroid Build Coastguard Worker   // Base case -- just logical-and the two conditions together.
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   if (InsertPt) {
470*9880d681SAndroid Build Coastguard Worker     makeAvailableAt(Cond0, InsertPt);
471*9880d681SAndroid Build Coastguard Worker     makeAvailableAt(Cond1, InsertPt);
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker     Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
474*9880d681SAndroid Build Coastguard Worker   }
475*9880d681SAndroid Build Coastguard Worker 
476*9880d681SAndroid Build Coastguard Worker   // We were not able to compute Cond0 AND Cond1 for the price of one.
477*9880d681SAndroid Build Coastguard Worker   return false;
478*9880d681SAndroid Build Coastguard Worker }
479*9880d681SAndroid Build Coastguard Worker 
parseRangeChecks(Value * CheckCond,SmallVectorImpl<GuardWideningImpl::RangeCheck> & Checks,SmallPtrSetImpl<Value * > & Visited)480*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::parseRangeChecks(
481*9880d681SAndroid Build Coastguard Worker     Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
482*9880d681SAndroid Build Coastguard Worker     SmallPtrSetImpl<Value *> &Visited) {
483*9880d681SAndroid Build Coastguard Worker   if (!Visited.insert(CheckCond).second)
484*9880d681SAndroid Build Coastguard Worker     return true;
485*9880d681SAndroid Build Coastguard Worker 
486*9880d681SAndroid Build Coastguard Worker   using namespace llvm::PatternMatch;
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker   {
489*9880d681SAndroid Build Coastguard Worker     Value *AndLHS, *AndRHS;
490*9880d681SAndroid Build Coastguard Worker     if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
491*9880d681SAndroid Build Coastguard Worker       return parseRangeChecks(AndLHS, Checks) &&
492*9880d681SAndroid Build Coastguard Worker              parseRangeChecks(AndRHS, Checks);
493*9880d681SAndroid Build Coastguard Worker   }
494*9880d681SAndroid Build Coastguard Worker 
495*9880d681SAndroid Build Coastguard Worker   auto *IC = dyn_cast<ICmpInst>(CheckCond);
496*9880d681SAndroid Build Coastguard Worker   if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
497*9880d681SAndroid Build Coastguard Worker       (IC->getPredicate() != ICmpInst::ICMP_ULT &&
498*9880d681SAndroid Build Coastguard Worker        IC->getPredicate() != ICmpInst::ICMP_UGT))
499*9880d681SAndroid Build Coastguard Worker     return false;
500*9880d681SAndroid Build Coastguard Worker 
501*9880d681SAndroid Build Coastguard Worker   Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
502*9880d681SAndroid Build Coastguard Worker   if (IC->getPredicate() == ICmpInst::ICMP_UGT)
503*9880d681SAndroid Build Coastguard Worker     std::swap(CmpLHS, CmpRHS);
504*9880d681SAndroid Build Coastguard Worker 
505*9880d681SAndroid Build Coastguard Worker   auto &DL = IC->getModule()->getDataLayout();
506*9880d681SAndroid Build Coastguard Worker 
507*9880d681SAndroid Build Coastguard Worker   GuardWideningImpl::RangeCheck Check(
508*9880d681SAndroid Build Coastguard Worker       CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
509*9880d681SAndroid Build Coastguard Worker       CmpRHS, IC);
510*9880d681SAndroid Build Coastguard Worker 
511*9880d681SAndroid Build Coastguard Worker   if (!isKnownNonNegative(Check.getLength(), DL))
512*9880d681SAndroid Build Coastguard Worker     return false;
513*9880d681SAndroid Build Coastguard Worker 
514*9880d681SAndroid Build Coastguard Worker   // What we have in \c Check now is a correct interpretation of \p CheckCond.
515*9880d681SAndroid Build Coastguard Worker   // Try to see if we can move some constant offsets into the \c Offset field.
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker   bool Changed;
518*9880d681SAndroid Build Coastguard Worker   auto &Ctx = CheckCond->getContext();
519*9880d681SAndroid Build Coastguard Worker 
520*9880d681SAndroid Build Coastguard Worker   do {
521*9880d681SAndroid Build Coastguard Worker     Value *OpLHS;
522*9880d681SAndroid Build Coastguard Worker     ConstantInt *OpRHS;
523*9880d681SAndroid Build Coastguard Worker     Changed = false;
524*9880d681SAndroid Build Coastguard Worker 
525*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
526*9880d681SAndroid Build Coastguard Worker     auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
527*9880d681SAndroid Build Coastguard Worker     assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
528*9880d681SAndroid Build Coastguard Worker            "Unreachable instruction?");
529*9880d681SAndroid Build Coastguard Worker #endif
530*9880d681SAndroid Build Coastguard Worker 
531*9880d681SAndroid Build Coastguard Worker     if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
532*9880d681SAndroid Build Coastguard Worker       Check.setBase(OpLHS);
533*9880d681SAndroid Build Coastguard Worker       APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
534*9880d681SAndroid Build Coastguard Worker       Check.setOffset(ConstantInt::get(Ctx, NewOffset));
535*9880d681SAndroid Build Coastguard Worker       Changed = true;
536*9880d681SAndroid Build Coastguard Worker     } else if (match(Check.getBase(),
537*9880d681SAndroid Build Coastguard Worker                      m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
538*9880d681SAndroid Build Coastguard Worker       unsigned BitWidth = OpLHS->getType()->getScalarSizeInBits();
539*9880d681SAndroid Build Coastguard Worker       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
540*9880d681SAndroid Build Coastguard Worker       computeKnownBits(OpLHS, KnownZero, KnownOne, DL);
541*9880d681SAndroid Build Coastguard Worker       if ((OpRHS->getValue() & KnownZero) == OpRHS->getValue()) {
542*9880d681SAndroid Build Coastguard Worker         Check.setBase(OpLHS);
543*9880d681SAndroid Build Coastguard Worker         APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
544*9880d681SAndroid Build Coastguard Worker         Check.setOffset(ConstantInt::get(Ctx, NewOffset));
545*9880d681SAndroid Build Coastguard Worker         Changed = true;
546*9880d681SAndroid Build Coastguard Worker       }
547*9880d681SAndroid Build Coastguard Worker     }
548*9880d681SAndroid Build Coastguard Worker   } while (Changed);
549*9880d681SAndroid Build Coastguard Worker 
550*9880d681SAndroid Build Coastguard Worker   Checks.push_back(Check);
551*9880d681SAndroid Build Coastguard Worker   return true;
552*9880d681SAndroid Build Coastguard Worker }
553*9880d681SAndroid Build Coastguard Worker 
combineRangeChecks(SmallVectorImpl<GuardWideningImpl::RangeCheck> & Checks,SmallVectorImpl<GuardWideningImpl::RangeCheck> & RangeChecksOut)554*9880d681SAndroid Build Coastguard Worker bool GuardWideningImpl::combineRangeChecks(
555*9880d681SAndroid Build Coastguard Worker     SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
556*9880d681SAndroid Build Coastguard Worker     SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
557*9880d681SAndroid Build Coastguard Worker   unsigned OldCount = Checks.size();
558*9880d681SAndroid Build Coastguard Worker   while (!Checks.empty()) {
559*9880d681SAndroid Build Coastguard Worker     // Pick all of the range checks with a specific base and length, and try to
560*9880d681SAndroid Build Coastguard Worker     // merge them.
561*9880d681SAndroid Build Coastguard Worker     Value *CurrentBase = Checks.front().getBase();
562*9880d681SAndroid Build Coastguard Worker     Value *CurrentLength = Checks.front().getLength();
563*9880d681SAndroid Build Coastguard Worker 
564*9880d681SAndroid Build Coastguard Worker     SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
565*9880d681SAndroid Build Coastguard Worker 
566*9880d681SAndroid Build Coastguard Worker     auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
567*9880d681SAndroid Build Coastguard Worker       return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
568*9880d681SAndroid Build Coastguard Worker     };
569*9880d681SAndroid Build Coastguard Worker 
570*9880d681SAndroid Build Coastguard Worker     std::copy_if(Checks.begin(), Checks.end(),
571*9880d681SAndroid Build Coastguard Worker                  std::back_inserter(CurrentChecks), IsCurrentCheck);
572*9880d681SAndroid Build Coastguard Worker     Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker     assert(CurrentChecks.size() != 0 && "We know we have at least one!");
575*9880d681SAndroid Build Coastguard Worker 
576*9880d681SAndroid Build Coastguard Worker     if (CurrentChecks.size() < 3) {
577*9880d681SAndroid Build Coastguard Worker       RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
578*9880d681SAndroid Build Coastguard Worker                             CurrentChecks.end());
579*9880d681SAndroid Build Coastguard Worker       continue;
580*9880d681SAndroid Build Coastguard Worker     }
581*9880d681SAndroid Build Coastguard Worker 
582*9880d681SAndroid Build Coastguard Worker     // CurrentChecks.size() will typically be 3 here, but so far there has been
583*9880d681SAndroid Build Coastguard Worker     // no need to hard-code that fact.
584*9880d681SAndroid Build Coastguard Worker 
585*9880d681SAndroid Build Coastguard Worker     std::sort(CurrentChecks.begin(), CurrentChecks.end(),
586*9880d681SAndroid Build Coastguard Worker               [&](const GuardWideningImpl::RangeCheck &LHS,
587*9880d681SAndroid Build Coastguard Worker                   const GuardWideningImpl::RangeCheck &RHS) {
588*9880d681SAndroid Build Coastguard Worker       return LHS.getOffsetValue().slt(RHS.getOffsetValue());
589*9880d681SAndroid Build Coastguard Worker     });
590*9880d681SAndroid Build Coastguard Worker 
591*9880d681SAndroid Build Coastguard Worker     // Note: std::sort should not invalidate the ChecksStart iterator.
592*9880d681SAndroid Build Coastguard Worker 
593*9880d681SAndroid Build Coastguard Worker     ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
594*9880d681SAndroid Build Coastguard Worker                 *MaxOffset = CurrentChecks.back().getOffset();
595*9880d681SAndroid Build Coastguard Worker 
596*9880d681SAndroid Build Coastguard Worker     unsigned BitWidth = MaxOffset->getValue().getBitWidth();
597*9880d681SAndroid Build Coastguard Worker     if ((MaxOffset->getValue() - MinOffset->getValue())
598*9880d681SAndroid Build Coastguard Worker             .ugt(APInt::getSignedMinValue(BitWidth)))
599*9880d681SAndroid Build Coastguard Worker       return false;
600*9880d681SAndroid Build Coastguard Worker 
601*9880d681SAndroid Build Coastguard Worker     APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
602*9880d681SAndroid Build Coastguard Worker     const APInt &HighOffset = MaxOffset->getValue();
603*9880d681SAndroid Build Coastguard Worker     auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
604*9880d681SAndroid Build Coastguard Worker       return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
605*9880d681SAndroid Build Coastguard Worker     };
606*9880d681SAndroid Build Coastguard Worker 
607*9880d681SAndroid Build Coastguard Worker     if (MaxDiff.isMinValue() ||
608*9880d681SAndroid Build Coastguard Worker         !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
609*9880d681SAndroid Build Coastguard Worker                      OffsetOK))
610*9880d681SAndroid Build Coastguard Worker       return false;
611*9880d681SAndroid Build Coastguard Worker 
612*9880d681SAndroid Build Coastguard Worker     // We have a series of f+1 checks as:
613*9880d681SAndroid Build Coastguard Worker     //
614*9880d681SAndroid Build Coastguard Worker     //   I+k_0 u< L   ... Chk_0
615*9880d681SAndroid Build Coastguard Worker     //   I_k_1 u< L   ... Chk_1
616*9880d681SAndroid Build Coastguard Worker     //   ...
617*9880d681SAndroid Build Coastguard Worker     //   I_k_f u< L   ... Chk_(f+1)
618*9880d681SAndroid Build Coastguard Worker     //
619*9880d681SAndroid Build Coastguard Worker     //     with forall i in [0,f): k_f-k_i u< k_f-k_0  ... Precond_0
620*9880d681SAndroid Build Coastguard Worker     //          k_f-k_0 u< INT_MIN+k_f                 ... Precond_1
621*9880d681SAndroid Build Coastguard Worker     //          k_f != k_0                             ... Precond_2
622*9880d681SAndroid Build Coastguard Worker     //
623*9880d681SAndroid Build Coastguard Worker     // Claim:
624*9880d681SAndroid Build Coastguard Worker     //   Chk_0 AND Chk_(f+1)  implies all the other checks
625*9880d681SAndroid Build Coastguard Worker     //
626*9880d681SAndroid Build Coastguard Worker     // Informal proof sketch:
627*9880d681SAndroid Build Coastguard Worker     //
628*9880d681SAndroid Build Coastguard Worker     // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
629*9880d681SAndroid Build Coastguard Worker     // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
630*9880d681SAndroid Build Coastguard Worker     // thus I+k_f is the greatest unsigned value in that range.
631*9880d681SAndroid Build Coastguard Worker     //
632*9880d681SAndroid Build Coastguard Worker     // This combined with Ckh_(f+1) shows that everything in that range is u< L.
633*9880d681SAndroid Build Coastguard Worker     // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
634*9880d681SAndroid Build Coastguard Worker     // lie in [I+k_0,I+k_f], this proving our claim.
635*9880d681SAndroid Build Coastguard Worker     //
636*9880d681SAndroid Build Coastguard Worker     // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
637*9880d681SAndroid Build Coastguard Worker     // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
638*9880d681SAndroid Build Coastguard Worker     // since k_0 != k_f).  In the former case, [I+k_0,I+k_f] is not a wrapping
639*9880d681SAndroid Build Coastguard Worker     // range by definition, and the latter case is impossible:
640*9880d681SAndroid Build Coastguard Worker     //
641*9880d681SAndroid Build Coastguard Worker     //   0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
642*9880d681SAndroid Build Coastguard Worker     //   xxxxxx             xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
643*9880d681SAndroid Build Coastguard Worker     //
644*9880d681SAndroid Build Coastguard Worker     // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
645*9880d681SAndroid Build Coastguard Worker     // with 'x' above) to be at least >u INT_MIN.
646*9880d681SAndroid Build Coastguard Worker 
647*9880d681SAndroid Build Coastguard Worker     RangeChecksOut.emplace_back(CurrentChecks.front());
648*9880d681SAndroid Build Coastguard Worker     RangeChecksOut.emplace_back(CurrentChecks.back());
649*9880d681SAndroid Build Coastguard Worker   }
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker   assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
652*9880d681SAndroid Build Coastguard Worker   return RangeChecksOut.size() != OldCount;
653*9880d681SAndroid Build Coastguard Worker }
654*9880d681SAndroid Build Coastguard Worker 
run(Function & F,AnalysisManager<Function> & AM)655*9880d681SAndroid Build Coastguard Worker PreservedAnalyses GuardWideningPass::run(Function &F,
656*9880d681SAndroid Build Coastguard Worker                                          AnalysisManager<Function> &AM) {
657*9880d681SAndroid Build Coastguard Worker   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
658*9880d681SAndroid Build Coastguard Worker   auto &LI = AM.getResult<LoopAnalysis>(F);
659*9880d681SAndroid Build Coastguard Worker   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
660*9880d681SAndroid Build Coastguard Worker   bool Changed = GuardWideningImpl(DT, PDT, LI).run();
661*9880d681SAndroid Build Coastguard Worker   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
662*9880d681SAndroid Build Coastguard Worker }
663*9880d681SAndroid Build Coastguard Worker 
scoreTypeToString(WideningScore WS)664*9880d681SAndroid Build Coastguard Worker StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
665*9880d681SAndroid Build Coastguard Worker   switch (WS) {
666*9880d681SAndroid Build Coastguard Worker   case WS_IllegalOrNegative:
667*9880d681SAndroid Build Coastguard Worker     return "IllegalOrNegative";
668*9880d681SAndroid Build Coastguard Worker   case WS_Neutral:
669*9880d681SAndroid Build Coastguard Worker     return "Neutral";
670*9880d681SAndroid Build Coastguard Worker   case WS_Positive:
671*9880d681SAndroid Build Coastguard Worker     return "Positive";
672*9880d681SAndroid Build Coastguard Worker   case WS_VeryPositive:
673*9880d681SAndroid Build Coastguard Worker     return "VeryPositive";
674*9880d681SAndroid Build Coastguard Worker   }
675*9880d681SAndroid Build Coastguard Worker 
676*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("Fully covered switch above!");
677*9880d681SAndroid Build Coastguard Worker }
678*9880d681SAndroid Build Coastguard Worker 
679*9880d681SAndroid Build Coastguard Worker char GuardWideningLegacyPass::ID = 0;
680*9880d681SAndroid Build Coastguard Worker 
681*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
682*9880d681SAndroid Build Coastguard Worker                       false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)683*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
684*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
685*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
686*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
687*9880d681SAndroid Build Coastguard Worker                     false, false)
688*9880d681SAndroid Build Coastguard Worker 
689*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createGuardWideningPass() {
690*9880d681SAndroid Build Coastguard Worker   return new GuardWideningLegacyPass();
691*9880d681SAndroid Build Coastguard Worker }
692