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