xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 24a98881cdb458376fc23ace6247b62084b4ad38)
1 //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
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 // Eliminate conditions based on constraints collected from dominating
10 // conditions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/ConstraintSystem.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/DebugCounter.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Transforms/Scalar.h"
33 
34 #include <string>
35 
36 using namespace llvm;
37 using namespace PatternMatch;
38 
39 #define DEBUG_TYPE "constraint-elimination"
40 
41 STATISTIC(NumCondsRemoved, "Number of instructions removed");
42 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
43               "Controls which conditions are eliminated");
44 
45 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
46 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
47 
48 namespace {
49 
50 class ConstraintInfo;
51 
52 struct StackEntry {
53   unsigned NumIn;
54   unsigned NumOut;
55   bool IsNot;
56   bool IsSigned = false;
57   /// Variables that can be removed from the system once the stack entry gets
58   /// removed.
59   SmallVector<Value *, 2> ValuesToRelease;
60 
61   StackEntry(unsigned NumIn, unsigned NumOut, bool IsNot, bool IsSigned,
62              SmallVector<Value *, 2> ValuesToRelease)
63       : NumIn(NumIn), NumOut(NumOut), IsNot(IsNot), IsSigned(IsSigned),
64         ValuesToRelease(ValuesToRelease) {}
65 };
66 
67 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
68 struct PreconditionTy {
69   CmpInst::Predicate Pred;
70   Value *Op0;
71   Value *Op1;
72 
73   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
74       : Pred(Pred), Op0(Op0), Op1(Op1) {}
75 };
76 
77 struct ConstraintTy {
78   SmallVector<int64_t, 8> Coefficients;
79   SmallVector<PreconditionTy, 2> Preconditions;
80 
81   bool IsSigned = false;
82   bool IsEq = false;
83 
84   ConstraintTy() = default;
85 
86   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
87       : Coefficients(Coefficients), IsSigned(IsSigned) {}
88 
89   unsigned size() const { return Coefficients.size(); }
90 
91   unsigned empty() const { return Coefficients.empty(); }
92 
93   /// Returns true if any constraint has a non-zero coefficient for any of the
94   /// newly added indices. Zero coefficients for new indices are removed. If it
95   /// returns true, no new variable need to be added to the system.
96   bool needsNewIndices(const DenseMap<Value *, unsigned> &NewIndices) {
97     for (unsigned I = 0; I < NewIndices.size(); ++I) {
98       int64_t Last = Coefficients.pop_back_val();
99       if (Last != 0)
100         return true;
101     }
102     return false;
103   }
104 
105   /// Returns true if all preconditions for this list of constraints are
106   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
107   bool isValid(const ConstraintInfo &Info) const;
108 };
109 
110 /// Wrapper encapsulating separate constraint systems and corresponding value
111 /// mappings for both unsigned and signed information. Facts are added to and
112 /// conditions are checked against the corresponding system depending on the
113 /// signed-ness of their predicates. While the information is kept separate
114 /// based on signed-ness, certain conditions can be transferred between the two
115 /// systems.
116 class ConstraintInfo {
117   DenseMap<Value *, unsigned> UnsignedValue2Index;
118   DenseMap<Value *, unsigned> SignedValue2Index;
119 
120   ConstraintSystem UnsignedCS;
121   ConstraintSystem SignedCS;
122 
123 public:
124   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
125     return Signed ? SignedValue2Index : UnsignedValue2Index;
126   }
127   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
128     return Signed ? SignedValue2Index : UnsignedValue2Index;
129   }
130 
131   ConstraintSystem &getCS(bool Signed) {
132     return Signed ? SignedCS : UnsignedCS;
133   }
134   const ConstraintSystem &getCS(bool Signed) const {
135     return Signed ? SignedCS : UnsignedCS;
136   }
137 
138   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
139   void popLastNVariables(bool Signed, unsigned N) {
140     getCS(Signed).popLastNVariables(N);
141   }
142 
143   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
144 
145   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, bool IsNegated,
146                unsigned NumIn, unsigned NumOut,
147                SmallVectorImpl<StackEntry> &DFSInStack);
148 
149   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
150   /// constraints, using indices from the corresponding constraint system.
151   /// Additional indices for newly discovered values are added to \p NewIndices.
152   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
153                              DenseMap<Value *, unsigned> &NewIndices) const;
154 
155   /// Turn a condition \p CmpI into a vector of constraints, using indices from
156   /// the corresponding constraint system. Additional indices for newly
157   /// discovered values are added to \p NewIndices.
158   ConstraintTy getConstraint(CmpInst *Cmp,
159                              DenseMap<Value *, unsigned> &NewIndices) const {
160     return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0),
161                          Cmp->getOperand(1), NewIndices);
162   }
163 
164   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
165   /// system if \p Pred is signed/unsigned.
166   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
167                              bool IsNegated, unsigned NumIn, unsigned NumOut,
168                              SmallVectorImpl<StackEntry> &DFSInStack);
169 };
170 
171 } // namespace
172 
173 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The
174 // sum of the pairs equals \p V.  The first pair is the constant-factor and X
175 // must be nullptr. If the expression cannot be decomposed, returns an empty
176 // vector.
177 static SmallVector<std::pair<int64_t, Value *>, 4>
178 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
179           bool IsSigned) {
180 
181   auto CanUseSExt = [](ConstantInt *CI) {
182     const APInt &Val = CI->getValue();
183     return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
184   };
185   // Decompose \p V used with a signed predicate.
186   if (IsSigned) {
187     if (auto *CI = dyn_cast<ConstantInt>(V)) {
188       if (CanUseSExt(CI))
189         return {{CI->getSExtValue(), nullptr}};
190     }
191 
192     return {{0, nullptr}, {1, V}};
193   }
194 
195   if (auto *CI = dyn_cast<ConstantInt>(V)) {
196     if (CI->uge(MaxConstraintValue))
197       return {};
198     return {{CI->getZExtValue(), nullptr}};
199   }
200   auto *GEP = dyn_cast<GetElementPtrInst>(V);
201   if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) {
202     Value *Op0, *Op1;
203     ConstantInt *CI;
204 
205     // If the index is zero-extended, it is guaranteed to be positive.
206     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
207               m_ZExt(m_Value(Op0)))) {
208       if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) &&
209           CanUseSExt(CI))
210         return {{0, nullptr},
211                 {1, GEP->getPointerOperand()},
212                 {std::pow(int64_t(2), CI->getSExtValue()), Op1}};
213       if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))) &&
214           CanUseSExt(CI))
215         return {{CI->getSExtValue(), nullptr},
216                 {1, GEP->getPointerOperand()},
217                 {1, Op1}};
218       return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
219     }
220 
221     if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) &&
222         !CI->isNegative() && CanUseSExt(CI))
223       return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}};
224 
225     SmallVector<std::pair<int64_t, Value *>, 4> Result;
226     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
227               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))) &&
228         CanUseSExt(CI))
229       Result = {{0, nullptr},
230                 {1, GEP->getPointerOperand()},
231                 {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
232     else if (match(GEP->getOperand(GEP->getNumOperands() - 1),
233                    m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))) &&
234              CanUseSExt(CI))
235       Result = {{CI->getSExtValue(), nullptr},
236                 {1, GEP->getPointerOperand()},
237                 {1, Op0}};
238     else {
239       Op0 = GEP->getOperand(GEP->getNumOperands() - 1);
240       Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
241     }
242     // If Op0 is signed non-negative, the GEP is increasing monotonically and
243     // can be de-composed.
244     Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
245                                ConstantInt::get(Op0->getType(), 0));
246     return Result;
247   }
248 
249   Value *Op0;
250   if (match(V, m_ZExt(m_Value(Op0))))
251     V = Op0;
252 
253   Value *Op1;
254   ConstantInt *CI;
255   if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))) &&
256       !CI->uge(MaxConstraintValue))
257     return {{CI->getZExtValue(), nullptr}, {1, Op0}};
258   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
259       CanUseSExt(CI)) {
260     Preconditions.emplace_back(
261         CmpInst::ICMP_UGE, Op0,
262         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
263     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
264   }
265   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
266     return {{0, nullptr}, {1, Op0}, {1, Op1}};
267 
268   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && CanUseSExt(CI))
269     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
270   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
271     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
272 
273   return {{0, nullptr}, {1, V}};
274 }
275 
276 ConstraintTy
277 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
278                               DenseMap<Value *, unsigned> &NewIndices) const {
279   bool IsEq = false;
280   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
281   switch (Pred) {
282   case CmpInst::ICMP_UGT:
283   case CmpInst::ICMP_UGE:
284   case CmpInst::ICMP_SGT:
285   case CmpInst::ICMP_SGE: {
286     Pred = CmpInst::getSwappedPredicate(Pred);
287     std::swap(Op0, Op1);
288     break;
289   }
290   case CmpInst::ICMP_EQ:
291     if (match(Op1, m_Zero())) {
292       Pred = CmpInst::ICMP_ULE;
293     } else {
294       IsEq = true;
295       Pred = CmpInst::ICMP_ULE;
296     }
297     break;
298   case CmpInst::ICMP_NE:
299     if (!match(Op1, m_Zero()))
300       return {};
301     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
302     std::swap(Op0, Op1);
303     break;
304   default:
305     break;
306   }
307 
308   // Only ULE and ULT predicates are supported at the moment.
309   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
310       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
311     return {};
312 
313   SmallVector<PreconditionTy, 4> Preconditions;
314   bool IsSigned = CmpInst::isSigned(Pred);
315   auto &Value2Index = getValue2Index(IsSigned);
316   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
317                         Preconditions, IsSigned);
318   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
319                         Preconditions, IsSigned);
320   // Skip if decomposing either of the values failed.
321   if (ADec.empty() || BDec.empty())
322     return {};
323 
324   int64_t Offset1 = ADec[0].first;
325   int64_t Offset2 = BDec[0].first;
326   Offset1 *= -1;
327 
328   // Create iterator ranges that skip the constant-factor.
329   auto VariablesA = llvm::drop_begin(ADec);
330   auto VariablesB = llvm::drop_begin(BDec);
331 
332   // First try to look up \p V in Value2Index and NewIndices. Otherwise add a
333   // new entry to NewIndices.
334   auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned {
335     auto V2I = Value2Index.find(V);
336     if (V2I != Value2Index.end())
337       return V2I->second;
338     auto Insert =
339         NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1});
340     return Insert.first->second;
341   };
342 
343   // Make sure all variables have entries in Value2Index or NewIndices.
344   for (const auto &KV :
345        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
346     GetOrAddIndex(KV.second);
347 
348   // Build result constraint, by first adding all coefficients from A and then
349   // subtracting all coefficients from B.
350   ConstraintTy Res(
351       SmallVector<int64_t, 8>(Value2Index.size() + NewIndices.size() + 1, 0),
352       IsSigned);
353   Res.IsEq = IsEq;
354   auto &R = Res.Coefficients;
355   for (const auto &KV : VariablesA)
356     R[GetOrAddIndex(KV.second)] += KV.first;
357 
358   for (const auto &KV : VariablesB)
359     R[GetOrAddIndex(KV.second)] -= KV.first;
360 
361   int64_t OffsetSum;
362   if (AddOverflow(Offset1, Offset2, OffsetSum))
363     return {};
364   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
365     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
366       return {};
367   R[0] = OffsetSum;
368   Res.Preconditions = std::move(Preconditions);
369   return Res;
370 }
371 
372 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
373   return Coefficients.size() > 0 &&
374          all_of(Preconditions, [&Info](const PreconditionTy &C) {
375            return Info.doesHold(C.Pred, C.Op0, C.Op1);
376          });
377 }
378 
379 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
380                               Value *B) const {
381   DenseMap<Value *, unsigned> NewIndices;
382   auto R = getConstraint(Pred, A, B, NewIndices);
383 
384   if (!NewIndices.empty())
385     return false;
386 
387   // TODO: properly check NewIndices.
388   return NewIndices.empty() && R.Preconditions.empty() && !R.IsEq &&
389          !R.empty() &&
390          getCS(CmpInst::isSigned(Pred)).isConditionImplied(R.Coefficients);
391 }
392 
393 void ConstraintInfo::transferToOtherSystem(
394     CmpInst::Predicate Pred, Value *A, Value *B, bool IsNegated, unsigned NumIn,
395     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
396   // Check if we can combine facts from the signed and unsigned systems to
397   // derive additional facts.
398   if (!A->getType()->isIntegerTy())
399     return;
400   // FIXME: This currently depends on the order we add facts. Ideally we
401   // would first add all known facts and only then try to add additional
402   // facts.
403   switch (Pred) {
404   default:
405     break;
406   case CmpInst::ICMP_SGT:
407     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
408       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0),
409               IsNegated, NumIn, NumOut, DFSInStack);
410     break;
411   case CmpInst::ICMP_SGE:
412     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
413       addFact(CmpInst::ICMP_UGE, A, B, IsNegated, NumIn, NumOut, DFSInStack);
414     }
415     break;
416   }
417 }
418 
419 namespace {
420 /// Represents either a condition that holds on entry to a block or a basic
421 /// block, with their respective Dominator DFS in and out numbers.
422 struct ConstraintOrBlock {
423   unsigned NumIn;
424   unsigned NumOut;
425   bool IsBlock;
426   bool Not;
427   union {
428     BasicBlock *BB;
429     CmpInst *Condition;
430   };
431 
432   ConstraintOrBlock(DomTreeNode *DTN)
433       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
434         BB(DTN->getBlock()) {}
435   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
436       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
437         Not(Not), Condition(Condition) {}
438 };
439 
440 /// Keep state required to build worklist.
441 struct State {
442   DominatorTree &DT;
443   SmallVector<ConstraintOrBlock, 64> WorkList;
444 
445   State(DominatorTree &DT) : DT(DT) {}
446 
447   /// Process block \p BB and add known facts to work-list.
448   void addInfoFor(BasicBlock &BB);
449 
450   /// Returns true if we can add a known condition from BB to its successor
451   /// block Succ. Each predecessor of Succ can either be BB or be dominated
452   /// by Succ (e.g. the case when adding a condition from a pre-header to a
453   /// loop header).
454   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
455     if (BB.getSingleSuccessor()) {
456       assert(BB.getSingleSuccessor() == Succ);
457       return DT.properlyDominates(&BB, Succ);
458     }
459     return any_of(successors(&BB),
460                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
461            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
462              return Pred == &BB || DT.dominates(Succ, Pred);
463            });
464   }
465 };
466 
467 } // namespace
468 
469 #ifndef NDEBUG
470 static void dumpWithNames(const ConstraintSystem &CS,
471                           DenseMap<Value *, unsigned> &Value2Index) {
472   SmallVector<std::string> Names(Value2Index.size(), "");
473   for (auto &KV : Value2Index) {
474     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
475   }
476   CS.dump(Names);
477 }
478 
479 static void dumpWithNames(ArrayRef<int64_t> C,
480                           DenseMap<Value *, unsigned> &Value2Index) {
481   ConstraintSystem CS;
482   CS.addVariableRowFill(C);
483   dumpWithNames(CS, Value2Index);
484 }
485 #endif
486 
487 void State::addInfoFor(BasicBlock &BB) {
488   WorkList.emplace_back(DT.getNode(&BB));
489 
490   // True as long as long as the current instruction is guaranteed to execute.
491   bool GuaranteedToExecute = true;
492   // Scan BB for assume calls.
493   // TODO: also use this scan to queue conditions to simplify, so we can
494   // interleave facts from assumes and conditions to simplify in a single
495   // basic block. And to skip another traversal of each basic block when
496   // simplifying.
497   for (Instruction &I : BB) {
498     Value *Cond;
499     // For now, just handle assumes with a single compare as condition.
500     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
501         isa<ICmpInst>(Cond)) {
502       if (GuaranteedToExecute) {
503         // The assume is guaranteed to execute when BB is entered, hence Cond
504         // holds on entry to BB.
505         WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
506       } else {
507         // Otherwise the condition only holds in the successors.
508         for (BasicBlock *Succ : successors(&BB)) {
509           if (!canAddSuccessor(BB, Succ))
510             continue;
511           WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false);
512         }
513       }
514     }
515     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
516   }
517 
518   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
519   if (!Br || !Br->isConditional())
520     return;
521 
522   // If the condition is an OR of 2 compares and the false successor only has
523   // the current block as predecessor, queue both negated conditions for the
524   // false successor.
525   Value *Op0, *Op1;
526   if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
527       isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
528     BasicBlock *FalseSuccessor = Br->getSuccessor(1);
529     if (canAddSuccessor(BB, FalseSuccessor)) {
530       WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0),
531                             true);
532       WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1),
533                             true);
534     }
535     return;
536   }
537 
538   // If the condition is an AND of 2 compares and the true successor only has
539   // the current block as predecessor, queue both conditions for the true
540   // successor.
541   if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
542       isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
543     BasicBlock *TrueSuccessor = Br->getSuccessor(0);
544     if (canAddSuccessor(BB, TrueSuccessor)) {
545       WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0),
546                             false);
547       WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1),
548                             false);
549     }
550     return;
551   }
552 
553   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
554   if (!CmpI)
555     return;
556   if (canAddSuccessor(BB, Br->getSuccessor(0)))
557     WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
558   if (canAddSuccessor(BB, Br->getSuccessor(1)))
559     WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
560 }
561 
562 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
563                              bool IsNegated, unsigned NumIn, unsigned NumOut,
564                              SmallVectorImpl<StackEntry> &DFSInStack) {
565   // If the constraint has a pre-condition, skip the constraint if it does not
566   // hold.
567   DenseMap<Value *, unsigned> NewIndices;
568   auto R = getConstraint(Pred, A, B, NewIndices);
569   if (!R.isValid(*this))
570     return;
571 
572   //LLVM_DEBUG(dbgs() << "Adding " << *Condition << " " << IsNegated << "\n");
573   bool Added = false;
574   assert(CmpInst::isSigned(Pred) == R.IsSigned &&
575          "condition and constraint signs must match");
576   auto &CSToUse = getCS(R.IsSigned);
577   if (R.Coefficients.empty())
578     return;
579 
580   Added |= CSToUse.addVariableRowFill(R.Coefficients);
581 
582   // If R has been added to the system, queue it for removal once it goes
583   // out-of-scope.
584   if (Added) {
585     SmallVector<Value *, 2> ValuesToRelease;
586     for (auto &KV : NewIndices) {
587       getValue2Index(R.IsSigned).insert(KV);
588       ValuesToRelease.push_back(KV.first);
589     }
590 
591     LLVM_DEBUG({
592       dbgs() << "  constraint: ";
593       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
594     });
595 
596     DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned,
597                             ValuesToRelease);
598 
599     if (R.IsEq) {
600       // Also add the inverted constraint for equality constraints.
601       for (auto &Coeff : R.Coefficients)
602         Coeff *= -1;
603       CSToUse.addVariableRowFill(R.Coefficients);
604 
605       DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned,
606                               SmallVector<Value *, 2>());
607     }
608   }
609 }
610 
611 static void
612 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
613                           SmallVectorImpl<Instruction *> &ToRemove) {
614   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
615                               ConstraintInfo &Info) {
616     DenseMap<Value *, unsigned> NewIndices;
617     auto R = Info.getConstraint(Pred, A, B, NewIndices);
618     if (R.size() < 2 || R.needsNewIndices(NewIndices) || !R.isValid(Info))
619       return false;
620 
621     auto &CSToUse = Info.getCS(CmpInst::isSigned(Pred));
622     return CSToUse.isConditionImplied(R.Coefficients);
623   };
624 
625   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
626     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
627     // can be simplified to a regular sub.
628     Value *A = II->getArgOperand(0);
629     Value *B = II->getArgOperand(1);
630     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
631         !DoesConditionHold(CmpInst::ICMP_SGE, B,
632                            ConstantInt::get(A->getType(), 0), Info))
633       return;
634 
635     IRBuilder<> Builder(II->getParent(), II->getIterator());
636     Value *Sub = nullptr;
637     for (User *U : make_early_inc_range(II->users())) {
638       if (match(U, m_ExtractValue<0>(m_Value()))) {
639         if (!Sub)
640           Sub = Builder.CreateSub(A, B);
641         U->replaceAllUsesWith(Sub);
642       } else if (match(U, m_ExtractValue<1>(m_Value())))
643         U->replaceAllUsesWith(Builder.getFalse());
644       else
645         continue;
646 
647       if (U->use_empty()) {
648         auto *I = cast<Instruction>(U);
649         ToRemove.push_back(I);
650         I->setOperand(0, PoisonValue::get(II->getType()));
651       }
652     }
653 
654     if (II->use_empty())
655       II->eraseFromParent();
656   }
657 }
658 
659 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
660   bool Changed = false;
661   DT.updateDFSNumbers();
662 
663   ConstraintInfo Info;
664   State S(DT);
665 
666   // First, collect conditions implied by branches and blocks with their
667   // Dominator DFS in and out numbers.
668   for (BasicBlock &BB : F) {
669     if (!DT.getNode(&BB))
670       continue;
671     S.addInfoFor(BB);
672   }
673 
674   // Next, sort worklist by dominance, so that dominating blocks and conditions
675   // come before blocks and conditions dominated by them. If a block and a
676   // condition have the same numbers, the condition comes before the block, as
677   // it holds on entry to the block.
678   sort(S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
679     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
680   });
681 
682   SmallVector<Instruction *> ToRemove;
683 
684   // Finally, process ordered worklist and eliminate implied conditions.
685   SmallVector<StackEntry, 16> DFSInStack;
686   for (ConstraintOrBlock &CB : S.WorkList) {
687     // First, pop entries from the stack that are out-of-scope for CB. Remove
688     // the corresponding entry from the constraint system.
689     while (!DFSInStack.empty()) {
690       auto &E = DFSInStack.back();
691       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
692                         << "\n");
693       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
694       assert(E.NumIn <= CB.NumIn);
695       if (CB.NumOut <= E.NumOut)
696         break;
697       LLVM_DEBUG({
698         dbgs() << "Removing ";
699         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
700                       Info.getValue2Index(E.IsSigned));
701         dbgs() << "\n";
702       });
703 
704       Info.popLastConstraint(E.IsSigned);
705       // Remove variables in the system that went out of scope.
706       auto &Mapping = Info.getValue2Index(E.IsSigned);
707       for (Value *V : E.ValuesToRelease)
708         Mapping.erase(V);
709       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
710       DFSInStack.pop_back();
711     }
712 
713     LLVM_DEBUG({
714       dbgs() << "Processing ";
715       if (CB.IsBlock)
716         dbgs() << *CB.BB;
717       else
718         dbgs() << *CB.Condition;
719       dbgs() << "\n";
720     });
721 
722     // For a block, check if any CmpInsts become known based on the current set
723     // of constraints.
724     if (CB.IsBlock) {
725       for (Instruction &I : make_early_inc_range(*CB.BB)) {
726         if (auto *II = dyn_cast<WithOverflowInst>(&I)) {
727           tryToSimplifyOverflowMath(II, Info, ToRemove);
728           continue;
729         }
730         auto *Cmp = dyn_cast<ICmpInst>(&I);
731         if (!Cmp)
732           continue;
733 
734         DenseMap<Value *, unsigned> NewIndices;
735         auto R = Info.getConstraint(Cmp, NewIndices);
736         if (R.IsEq || R.empty() || R.needsNewIndices(NewIndices) ||
737             !R.isValid(Info))
738           continue;
739 
740         auto &CSToUse = Info.getCS(R.IsSigned);
741         if (CSToUse.isConditionImplied(R.Coefficients)) {
742           if (!DebugCounter::shouldExecute(EliminatedCounter))
743             continue;
744 
745           LLVM_DEBUG({
746             dbgs() << "Condition " << *Cmp
747                    << " implied by dominating constraints\n";
748             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
749           });
750           Cmp->replaceUsesWithIf(
751               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
752                 // Conditions in an assume trivially simplify to true. Skip uses
753                 // in assume calls to not destroy the available information.
754                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
755                 return !II || II->getIntrinsicID() != Intrinsic::assume;
756               });
757           NumCondsRemoved++;
758           Changed = true;
759         }
760         if (CSToUse.isConditionImplied(
761                 ConstraintSystem::negate(R.Coefficients))) {
762           if (!DebugCounter::shouldExecute(EliminatedCounter))
763             continue;
764 
765           LLVM_DEBUG({
766             dbgs() << "Condition !" << *Cmp
767                    << " implied by dominating constraints\n";
768             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
769           });
770           Cmp->replaceAllUsesWith(
771               ConstantInt::getFalse(F.getParent()->getContext()));
772           NumCondsRemoved++;
773           Changed = true;
774         }
775       }
776       continue;
777     }
778 
779     // Set up a function to restore the predicate at the end of the scope if it
780     // has been negated. Negate the predicate in-place, if required.
781     auto *CI = dyn_cast<ICmpInst>(CB.Condition);
782     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
783       if (CB.Not && CI)
784         CI->setPredicate(CI->getInversePredicate());
785     });
786     if (CB.Not) {
787       if (CI) {
788         CI->setPredicate(CI->getInversePredicate());
789       } else {
790         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
791         continue;
792       }
793     }
794 
795     ICmpInst::Predicate Pred;
796     Value *A, *B;
797     if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
798       // Otherwise, add the condition to the system and stack, if we can
799       // transform it into a constraint.
800       Info.addFact(Pred, A, B, CB.Not, CB.NumIn, CB.NumOut, DFSInStack);
801       Info.transferToOtherSystem(Pred, A, B, CB.Not, CB.NumIn, CB.NumOut,
802                                  DFSInStack);
803     }
804   }
805 
806 #ifndef NDEBUG
807   unsigned SignedEntries =
808       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
809   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
810          "updates to CS and DFSInStack are out of sync");
811   assert(Info.getCS(true).size() == SignedEntries &&
812          "updates to CS and DFSInStack are out of sync");
813 #endif
814 
815   for (Instruction *I : ToRemove)
816     I->eraseFromParent();
817   return Changed;
818 }
819 
820 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
821                                                  FunctionAnalysisManager &AM) {
822   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
823   if (!eliminateConstraints(F, DT))
824     return PreservedAnalyses::all();
825 
826   PreservedAnalyses PA;
827   PA.preserve<DominatorTreeAnalysis>();
828   PA.preserveSet<CFGAnalyses>();
829   return PA;
830 }
831 
832 namespace {
833 
834 class ConstraintElimination : public FunctionPass {
835 public:
836   static char ID;
837 
838   ConstraintElimination() : FunctionPass(ID) {
839     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
840   }
841 
842   bool runOnFunction(Function &F) override {
843     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
844     return eliminateConstraints(F, DT);
845   }
846 
847   void getAnalysisUsage(AnalysisUsage &AU) const override {
848     AU.setPreservesCFG();
849     AU.addRequired<DominatorTreeWrapperPass>();
850     AU.addPreserved<GlobalsAAWrapperPass>();
851     AU.addPreserved<DominatorTreeWrapperPass>();
852   }
853 };
854 
855 } // end anonymous namespace
856 
857 char ConstraintElimination::ID = 0;
858 
859 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
860                       "Constraint Elimination", false, false)
861 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
862 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
863 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
864                     "Constraint Elimination", false, false)
865 
866 FunctionPass *llvm::createConstraintEliminationPass() {
867   return new ConstraintElimination();
868 }
869