xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 42d92614173271fe1e8c40a5ad907b8c08f54f94)
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/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/DebugCounter.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Transforms/Scalar.h"
35 
36 #include <cmath>
37 #include <string>
38 
39 using namespace llvm;
40 using namespace PatternMatch;
41 
42 #define DEBUG_TYPE "constraint-elimination"
43 
44 STATISTIC(NumCondsRemoved, "Number of instructions removed");
45 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
46               "Controls which conditions are eliminated");
47 
48 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
49 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
50 
51 // A helper to multiply 2 signed integers where overflowing is allowed.
52 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
53   int64_t Result;
54   MulOverflow(A, B, Result);
55   return Result;
56 }
57 
58 // A helper to add 2 signed integers where overflowing is allowed.
59 static int64_t addWithOverflow(int64_t A, int64_t B) {
60   int64_t Result;
61   AddOverflow(A, B, Result);
62   return Result;
63 }
64 
65 namespace {
66 
67 class ConstraintInfo;
68 
69 struct StackEntry {
70   unsigned NumIn;
71   unsigned NumOut;
72   bool IsSigned = false;
73   /// Variables that can be removed from the system once the stack entry gets
74   /// removed.
75   SmallVector<Value *, 2> ValuesToRelease;
76 
77   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
78              SmallVector<Value *, 2> ValuesToRelease)
79       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
80         ValuesToRelease(ValuesToRelease) {}
81 };
82 
83 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
84 struct PreconditionTy {
85   CmpInst::Predicate Pred;
86   Value *Op0;
87   Value *Op1;
88 
89   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
90       : Pred(Pred), Op0(Op0), Op1(Op1) {}
91 };
92 
93 struct ConstraintTy {
94   SmallVector<int64_t, 8> Coefficients;
95   SmallVector<PreconditionTy, 2> Preconditions;
96 
97   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
98 
99   bool IsSigned = false;
100   bool IsEq = false;
101 
102   ConstraintTy() = default;
103 
104   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
105       : Coefficients(Coefficients), IsSigned(IsSigned) {}
106 
107   unsigned size() const { return Coefficients.size(); }
108 
109   unsigned empty() const { return Coefficients.empty(); }
110 
111   /// Returns true if all preconditions for this list of constraints are
112   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
113   bool isValid(const ConstraintInfo &Info) const;
114 };
115 
116 /// Wrapper encapsulating separate constraint systems and corresponding value
117 /// mappings for both unsigned and signed information. Facts are added to and
118 /// conditions are checked against the corresponding system depending on the
119 /// signed-ness of their predicates. While the information is kept separate
120 /// based on signed-ness, certain conditions can be transferred between the two
121 /// systems.
122 class ConstraintInfo {
123   DenseMap<Value *, unsigned> UnsignedValue2Index;
124   DenseMap<Value *, unsigned> SignedValue2Index;
125 
126   ConstraintSystem UnsignedCS;
127   ConstraintSystem SignedCS;
128 
129   const DataLayout &DL;
130 
131 public:
132   ConstraintInfo(const DataLayout &DL) : DL(DL) {}
133 
134   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
135     return Signed ? SignedValue2Index : UnsignedValue2Index;
136   }
137   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
138     return Signed ? SignedValue2Index : UnsignedValue2Index;
139   }
140 
141   ConstraintSystem &getCS(bool Signed) {
142     return Signed ? SignedCS : UnsignedCS;
143   }
144   const ConstraintSystem &getCS(bool Signed) const {
145     return Signed ? SignedCS : UnsignedCS;
146   }
147 
148   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
149   void popLastNVariables(bool Signed, unsigned N) {
150     getCS(Signed).popLastNVariables(N);
151   }
152 
153   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
154 
155   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
156                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
157 
158   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
159   /// constraints, using indices from the corresponding constraint system.
160   /// New variables that need to be added to the system are collected in
161   /// \p NewVariables.
162   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
163                              SmallVectorImpl<Value *> &NewVariables) const;
164 
165   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
166   /// constraints using getConstraint. Returns an empty constraint if the result
167   /// cannot be used to query the existing constraint system, e.g. because it
168   /// would require adding new variables. Also tries to convert signed
169   /// predicates to unsigned ones if possible to allow using the unsigned system
170   /// which increases the effectiveness of the signed <-> unsigned transfer
171   /// logic.
172   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
173                                        Value *Op1) const;
174 
175   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
176   /// system if \p Pred is signed/unsigned.
177   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
178                              unsigned NumIn, unsigned NumOut,
179                              SmallVectorImpl<StackEntry> &DFSInStack);
180 };
181 
182 /// Represents a (Coefficient * Variable) entry after IR decomposition.
183 struct DecompEntry {
184   int64_t Coefficient;
185   Value *Variable;
186   /// True if the variable is known positive in the current constraint.
187   bool IsKnownPositive;
188 
189   DecompEntry(int64_t Coefficient, Value *Variable,
190               bool IsKnownPositive = false)
191       : Coefficient(Coefficient), Variable(Variable),
192         IsKnownPositive(IsKnownPositive) {}
193 };
194 
195 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
196 struct Decomposition {
197   int64_t Offset = 0;
198   SmallVector<DecompEntry, 3> Vars;
199 
200   Decomposition(int64_t Offset) : Offset(Offset) {}
201   Decomposition(Value *V, bool IsKnownPositive = false) {
202     Vars.emplace_back(1, V, IsKnownPositive);
203   }
204   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
205       : Offset(Offset), Vars(Vars) {}
206 
207   void add(int64_t OtherOffset) {
208     Offset = addWithOverflow(Offset, OtherOffset);
209   }
210 
211   void add(const Decomposition &Other) {
212     add(Other.Offset);
213     append_range(Vars, Other.Vars);
214   }
215 
216   void mul(int64_t Factor) {
217     Offset = multiplyWithOverflow(Offset, Factor);
218     for (auto &Var : Vars)
219       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
220   }
221 };
222 
223 } // namespace
224 
225 static Decomposition decompose(Value *V,
226                                SmallVectorImpl<PreconditionTy> &Preconditions,
227                                bool IsSigned, const DataLayout &DL);
228 
229 static bool canUseSExt(ConstantInt *CI) {
230   const APInt &Val = CI->getValue();
231   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
232 }
233 
234 static Decomposition
235 decomposeGEP(GetElementPtrInst &GEP,
236              SmallVectorImpl<PreconditionTy> &Preconditions, bool IsSigned,
237              const DataLayout &DL) {
238   // Do not reason about pointers where the index size is larger than 64 bits,
239   // as the coefficients used to encode constraints are 64 bit integers.
240   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
241     return &GEP;
242 
243   if (!GEP.isInBounds())
244     return &GEP;
245 
246   // Handle the (gep (gep ....), C) case by incrementing the constant
247   // coefficient of the inner GEP, if C is a constant.
248   auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
249   if (InnerGEP && GEP.getNumOperands() == 2 &&
250       isa<ConstantInt>(GEP.getOperand(1))) {
251     APInt Offset = cast<ConstantInt>(GEP.getOperand(1))->getValue();
252     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
253 
254     auto GTI = gep_type_begin(GEP);
255     // Bail out for scalable vectors for now.
256     if (isa<ScalableVectorType>(GTI.getIndexedType()))
257       return &GEP;
258     int64_t Scale = static_cast<int64_t>(
259         DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
260 
261     Result.add(multiplyWithOverflow(Scale, Offset.getSExtValue()));
262     if (Offset.isNegative()) {
263       // Add pre-condition ensuring the GEP is increasing monotonically and
264       // can be de-composed.
265       Preconditions.emplace_back(
266           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
267           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
268                            -1 * Offset.getSExtValue()));
269     }
270     return Result;
271   }
272 
273   Decomposition Result = GEP.getPointerOperand();
274   gep_type_iterator GTI = gep_type_begin(GEP);
275   for (User::const_op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
276        ++I, ++GTI) {
277     Value *Index = *I;
278 
279     // Bail out for scalable vectors for now.
280     if (isa<ScalableVectorType>(GTI.getIndexedType()))
281       return &GEP;
282 
283     // Struct indices must be constants (and reference an existing field). Add
284     // them to the constant factor.
285     if (StructType *STy = GTI.getStructTypeOrNull()) {
286       // For a struct, add the member offset.
287       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
288       if (FieldNo == 0)
289         continue;
290 
291       // Add offset to constant factor.
292       Result.add(int64_t(DL.getStructLayout(STy)->getElementOffset(FieldNo)));
293       continue;
294     }
295 
296     // For an array/pointer, add the element offset, explicitly scaled.
297     unsigned Scale = DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize();
298 
299     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
300     IdxResult.mul(Scale);
301     Result.add(IdxResult);
302 
303     // If Op0 is signed non-negative, the GEP is increasing monotonically and
304     // can be de-composed.
305     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
306       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
307                                  ConstantInt::get(Index->getType(), 0));
308   }
309   return Result;
310 }
311 
312 // Decomposes \p V into a vector of entries of the form { Coefficient, Variable
313 // } where Coefficient * Variable. The sum of the pairs equals \p V.  The first
314 // pair is the constant-factor and X must be nullptr. If the expression cannot
315 // be decomposed, returns an empty vector.
316 static Decomposition decompose(Value *V,
317                                SmallVectorImpl<PreconditionTy> &Preconditions,
318                                bool IsSigned, const DataLayout &DL) {
319 
320   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
321                                                       bool IsSignedB) {
322     auto ResA = decompose(A, Preconditions, IsSigned, DL);
323     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
324     ResA.add(ResB);
325     return ResA;
326   };
327 
328   // Decompose \p V used with a signed predicate.
329   if (IsSigned) {
330     if (auto *CI = dyn_cast<ConstantInt>(V)) {
331       if (canUseSExt(CI))
332         return CI->getSExtValue();
333     }
334     Value *Op0;
335     Value *Op1;
336     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
337       return MergeResults(Op0, Op1, IsSigned);
338 
339     return V;
340   }
341 
342   if (auto *CI = dyn_cast<ConstantInt>(V)) {
343     if (CI->uge(MaxConstraintValue))
344       return V;
345     return int64_t(CI->getZExtValue());
346   }
347 
348   if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
349     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
350 
351   Value *Op0;
352   bool IsKnownPositive = false;
353   if (match(V, m_ZExt(m_Value(Op0)))) {
354     IsKnownPositive = true;
355     V = Op0;
356   }
357 
358   Value *Op1;
359   ConstantInt *CI;
360   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
361     return MergeResults(Op0, Op1, IsSigned);
362   }
363   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
364     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
365       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
366                                  ConstantInt::get(Op0->getType(), 0));
367     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
368       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
369                                  ConstantInt::get(Op1->getType(), 0));
370 
371     return MergeResults(Op0, Op1, IsSigned);
372   }
373 
374   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
375       canUseSExt(CI)) {
376     Preconditions.emplace_back(
377         CmpInst::ICMP_UGE, Op0,
378         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
379     return MergeResults(Op0, CI, true);
380   }
381 
382   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
383     int64_t Mult = int64_t(std::pow(int64_t(2), CI->getSExtValue()));
384     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
385     Result.mul(Mult);
386     return Result;
387   }
388 
389   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
390       (!CI->isNegative())) {
391     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
392     Result.mul(CI->getSExtValue());
393     return Result;
394   }
395 
396   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
397     return {-1 * CI->getSExtValue(), {{1, Op0}}};
398   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
399     return {0, {{1, Op0}, {-1, Op1}}};
400 
401   return {V, IsKnownPositive};
402 }
403 
404 ConstraintTy
405 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
406                               SmallVectorImpl<Value *> &NewVariables) const {
407   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
408   bool IsEq = false;
409   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
410   switch (Pred) {
411   case CmpInst::ICMP_UGT:
412   case CmpInst::ICMP_UGE:
413   case CmpInst::ICMP_SGT:
414   case CmpInst::ICMP_SGE: {
415     Pred = CmpInst::getSwappedPredicate(Pred);
416     std::swap(Op0, Op1);
417     break;
418   }
419   case CmpInst::ICMP_EQ:
420     if (match(Op1, m_Zero())) {
421       Pred = CmpInst::ICMP_ULE;
422     } else {
423       IsEq = true;
424       Pred = CmpInst::ICMP_ULE;
425     }
426     break;
427   case CmpInst::ICMP_NE:
428     if (!match(Op1, m_Zero()))
429       return {};
430     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
431     std::swap(Op0, Op1);
432     break;
433   default:
434     break;
435   }
436 
437   // Only ULE and ULT predicates are supported at the moment.
438   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
439       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
440     return {};
441 
442   SmallVector<PreconditionTy, 4> Preconditions;
443   bool IsSigned = CmpInst::isSigned(Pred);
444   auto &Value2Index = getValue2Index(IsSigned);
445   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
446                         Preconditions, IsSigned, DL);
447   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
448                         Preconditions, IsSigned, DL);
449   int64_t Offset1 = ADec.Offset;
450   int64_t Offset2 = BDec.Offset;
451   Offset1 *= -1;
452 
453   auto &VariablesA = ADec.Vars;
454   auto &VariablesB = BDec.Vars;
455 
456   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
457   // new entry to NewVariables.
458   DenseMap<Value *, unsigned> NewIndexMap;
459   auto GetOrAddIndex = [&Value2Index, &NewVariables,
460                         &NewIndexMap](Value *V) -> unsigned {
461     auto V2I = Value2Index.find(V);
462     if (V2I != Value2Index.end())
463       return V2I->second;
464     auto Insert =
465         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
466     if (Insert.second)
467       NewVariables.push_back(V);
468     return Insert.first->second;
469   };
470 
471   // Make sure all variables have entries in Value2Index or NewVariables.
472   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
473     GetOrAddIndex(KV.Variable);
474 
475   // Build result constraint, by first adding all coefficients from A and then
476   // subtracting all coefficients from B.
477   ConstraintTy Res(
478       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
479       IsSigned);
480   // Collect variables that are known to be positive in all uses in the
481   // constraint.
482   DenseMap<Value *, bool> KnownPositiveVariables;
483   Res.IsEq = IsEq;
484   auto &R = Res.Coefficients;
485   for (const auto &KV : VariablesA) {
486     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
487     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
488     I.first->second &= KV.IsKnownPositive;
489   }
490 
491   for (const auto &KV : VariablesB) {
492     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
493     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
494     I.first->second &= KV.IsKnownPositive;
495   }
496 
497   int64_t OffsetSum;
498   if (AddOverflow(Offset1, Offset2, OffsetSum))
499     return {};
500   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
501     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
502       return {};
503   R[0] = OffsetSum;
504   Res.Preconditions = std::move(Preconditions);
505 
506   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
507   // variables.
508   while (!NewVariables.empty()) {
509     int64_t Last = R.back();
510     if (Last != 0)
511       break;
512     R.pop_back();
513     Value *RemovedV = NewVariables.pop_back_val();
514     NewIndexMap.erase(RemovedV);
515   }
516 
517   // Add extra constraints for variables that are known positive.
518   for (auto &KV : KnownPositiveVariables) {
519     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
520                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
521       continue;
522     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
523     C[GetOrAddIndex(KV.first)] = -1;
524     Res.ExtraInfo.push_back(C);
525   }
526   return Res;
527 }
528 
529 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
530                                                      Value *Op0,
531                                                      Value *Op1) const {
532   // If both operands are known to be non-negative, change signed predicates to
533   // unsigned ones. This increases the reasoning effectiveness in combination
534   // with the signed <-> unsigned transfer logic.
535   if (CmpInst::isSigned(Pred) &&
536       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
537       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
538     Pred = CmpInst::getUnsignedPredicate(Pred);
539 
540   SmallVector<Value *> NewVariables;
541   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
542   if (R.IsEq || !NewVariables.empty())
543     return {};
544   return R;
545 }
546 
547 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
548   return Coefficients.size() > 0 &&
549          all_of(Preconditions, [&Info](const PreconditionTy &C) {
550            return Info.doesHold(C.Pred, C.Op0, C.Op1);
551          });
552 }
553 
554 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
555                               Value *B) const {
556   auto R = getConstraintForSolving(Pred, A, B);
557   return R.Preconditions.empty() && !R.empty() &&
558          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
559 }
560 
561 void ConstraintInfo::transferToOtherSystem(
562     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
563     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
564   // Check if we can combine facts from the signed and unsigned systems to
565   // derive additional facts.
566   if (!A->getType()->isIntegerTy())
567     return;
568   // FIXME: This currently depends on the order we add facts. Ideally we
569   // would first add all known facts and only then try to add additional
570   // facts.
571   switch (Pred) {
572   default:
573     break;
574   case CmpInst::ICMP_ULT:
575     //  If B is a signed positive constant, A >=s 0 and A <s B.
576     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
577       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
578               NumOut, DFSInStack);
579       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
580     }
581     break;
582   case CmpInst::ICMP_SLT:
583     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
584       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
585     break;
586   case CmpInst::ICMP_SGT:
587     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
588       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
589               NumOut, DFSInStack);
590     break;
591   case CmpInst::ICMP_SGE:
592     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
593       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
594     }
595     break;
596   }
597 }
598 
599 namespace {
600 /// Represents either a condition that holds on entry to a block or a basic
601 /// block, with their respective Dominator DFS in and out numbers.
602 struct ConstraintOrBlock {
603   unsigned NumIn;
604   unsigned NumOut;
605   bool IsBlock;
606   bool Not;
607   union {
608     BasicBlock *BB;
609     CmpInst *Condition;
610   };
611 
612   ConstraintOrBlock(DomTreeNode *DTN)
613       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
614         BB(DTN->getBlock()) {}
615   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
616       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
617         Not(Not), Condition(Condition) {}
618 };
619 
620 /// Keep state required to build worklist.
621 struct State {
622   DominatorTree &DT;
623   SmallVector<ConstraintOrBlock, 64> WorkList;
624 
625   State(DominatorTree &DT) : DT(DT) {}
626 
627   /// Process block \p BB and add known facts to work-list.
628   void addInfoFor(BasicBlock &BB);
629 
630   /// Returns true if we can add a known condition from BB to its successor
631   /// block Succ. Each predecessor of Succ can either be BB or be dominated
632   /// by Succ (e.g. the case when adding a condition from a pre-header to a
633   /// loop header).
634   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
635     if (BB.getSingleSuccessor()) {
636       assert(BB.getSingleSuccessor() == Succ);
637       return DT.properlyDominates(&BB, Succ);
638     }
639     return any_of(successors(&BB),
640                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
641            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
642              return Pred == &BB || DT.dominates(Succ, Pred);
643            });
644   }
645 };
646 
647 } // namespace
648 
649 #ifndef NDEBUG
650 static void dumpWithNames(const ConstraintSystem &CS,
651                           DenseMap<Value *, unsigned> &Value2Index) {
652   SmallVector<std::string> Names(Value2Index.size(), "");
653   for (auto &KV : Value2Index) {
654     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
655   }
656   CS.dump(Names);
657 }
658 
659 static void dumpWithNames(ArrayRef<int64_t> C,
660                           DenseMap<Value *, unsigned> &Value2Index) {
661   ConstraintSystem CS;
662   CS.addVariableRowFill(C);
663   dumpWithNames(CS, Value2Index);
664 }
665 #endif
666 
667 void State::addInfoFor(BasicBlock &BB) {
668   WorkList.emplace_back(DT.getNode(&BB));
669 
670   // True as long as long as the current instruction is guaranteed to execute.
671   bool GuaranteedToExecute = true;
672   // Scan BB for assume calls.
673   // TODO: also use this scan to queue conditions to simplify, so we can
674   // interleave facts from assumes and conditions to simplify in a single
675   // basic block. And to skip another traversal of each basic block when
676   // simplifying.
677   for (Instruction &I : BB) {
678     Value *Cond;
679     // For now, just handle assumes with a single compare as condition.
680     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
681         isa<ICmpInst>(Cond)) {
682       if (GuaranteedToExecute) {
683         // The assume is guaranteed to execute when BB is entered, hence Cond
684         // holds on entry to BB.
685         WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
686       } else {
687         // Otherwise the condition only holds in the successors.
688         for (BasicBlock *Succ : successors(&BB)) {
689           if (!canAddSuccessor(BB, Succ))
690             continue;
691           WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false);
692         }
693       }
694     }
695     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
696   }
697 
698   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
699   if (!Br || !Br->isConditional())
700     return;
701 
702   Value *Cond = Br->getCondition();
703 
704   // If the condition is a chain of ORs/AND and the successor only has the
705   // current block as predecessor, queue conditions for the successor.
706   Value *Op0, *Op1;
707   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
708       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
709     bool IsOr = match(Cond, m_LogicalOr());
710     bool IsAnd = match(Cond, m_LogicalAnd());
711     // If there's a select that matches both AND and OR, we need to commit to
712     // one of the options. Arbitrarily pick OR.
713     if (IsOr && IsAnd)
714       IsAnd = false;
715 
716     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
717     if (canAddSuccessor(BB, Successor)) {
718       SmallVector<Value *> CondWorkList;
719       SmallPtrSet<Value *, 8> SeenCond;
720       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
721         if (SeenCond.insert(V).second)
722           CondWorkList.push_back(V);
723       };
724       QueueValue(Op1);
725       QueueValue(Op0);
726       while (!CondWorkList.empty()) {
727         Value *Cur = CondWorkList.pop_back_val();
728         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
729           WorkList.emplace_back(DT.getNode(Successor), Cmp, IsOr);
730           continue;
731         }
732         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
733           QueueValue(Op1);
734           QueueValue(Op0);
735           continue;
736         }
737         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
738           QueueValue(Op1);
739           QueueValue(Op0);
740           continue;
741         }
742       }
743     }
744     return;
745   }
746 
747   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
748   if (!CmpI)
749     return;
750   if (canAddSuccessor(BB, Br->getSuccessor(0)))
751     WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
752   if (canAddSuccessor(BB, Br->getSuccessor(1)))
753     WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
754 }
755 
756 static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info) {
757   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
758 
759   CmpInst::Predicate Pred = Cmp->getPredicate();
760   Value *A = Cmp->getOperand(0);
761   Value *B = Cmp->getOperand(1);
762 
763   auto R = Info.getConstraintForSolving(Pred, A, B);
764   if (R.empty() || !R.isValid(Info)){
765     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
766     return false;
767   }
768 
769   auto &CSToUse = Info.getCS(R.IsSigned);
770 
771   // If there was extra information collected during decomposition, apply
772   // it now and remove it immediately once we are done with reasoning
773   // about the constraint.
774   for (auto &Row : R.ExtraInfo)
775     CSToUse.addVariableRow(Row);
776   auto InfoRestorer = make_scope_exit([&]() {
777     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
778       CSToUse.popLastConstraint();
779   });
780 
781   bool Changed = false;
782   if (CSToUse.isConditionImplied(R.Coefficients)) {
783     if (!DebugCounter::shouldExecute(EliminatedCounter))
784       return false;
785 
786     LLVM_DEBUG({
787       dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n";
788       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
789     });
790     Constant *TrueC =
791         ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType()));
792     Cmp->replaceUsesWithIf(TrueC, [](Use &U) {
793       // Conditions in an assume trivially simplify to true. Skip uses
794       // in assume calls to not destroy the available information.
795       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
796       return !II || II->getIntrinsicID() != Intrinsic::assume;
797     });
798     NumCondsRemoved++;
799     Changed = true;
800   }
801   if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) {
802     if (!DebugCounter::shouldExecute(EliminatedCounter))
803       return false;
804 
805     LLVM_DEBUG({
806       dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n";
807       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
808     });
809     Constant *FalseC =
810         ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType()));
811     Cmp->replaceAllUsesWith(FalseC);
812     NumCondsRemoved++;
813     Changed = true;
814   }
815   return Changed;
816 }
817 
818 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
819                              unsigned NumIn, unsigned NumOut,
820                              SmallVectorImpl<StackEntry> &DFSInStack) {
821   // If the constraint has a pre-condition, skip the constraint if it does not
822   // hold.
823   SmallVector<Value *> NewVariables;
824   auto R = getConstraint(Pred, A, B, NewVariables);
825   if (!R.isValid(*this))
826     return;
827 
828   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
829              A->printAsOperand(dbgs(), false); dbgs() << ", ";
830              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
831   bool Added = false;
832   auto &CSToUse = getCS(R.IsSigned);
833   if (R.Coefficients.empty())
834     return;
835 
836   Added |= CSToUse.addVariableRowFill(R.Coefficients);
837 
838   // If R has been added to the system, add the new variables and queue it for
839   // removal once it goes out-of-scope.
840   if (Added) {
841     SmallVector<Value *, 2> ValuesToRelease;
842     auto &Value2Index = getValue2Index(R.IsSigned);
843     for (Value *V : NewVariables) {
844       Value2Index.insert({V, Value2Index.size() + 1});
845       ValuesToRelease.push_back(V);
846     }
847 
848     LLVM_DEBUG({
849       dbgs() << "  constraint: ";
850       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
851       dbgs() << "\n";
852     });
853 
854     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease);
855 
856     if (R.IsEq) {
857       // Also add the inverted constraint for equality constraints.
858       for (auto &Coeff : R.Coefficients)
859         Coeff *= -1;
860       CSToUse.addVariableRowFill(R.Coefficients);
861 
862       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
863                               SmallVector<Value *, 2>());
864     }
865   }
866 }
867 
868 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
869                                    SmallVectorImpl<Instruction *> &ToRemove) {
870   bool Changed = false;
871   IRBuilder<> Builder(II->getParent(), II->getIterator());
872   Value *Sub = nullptr;
873   for (User *U : make_early_inc_range(II->users())) {
874     if (match(U, m_ExtractValue<0>(m_Value()))) {
875       if (!Sub)
876         Sub = Builder.CreateSub(A, B);
877       U->replaceAllUsesWith(Sub);
878       Changed = true;
879     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
880       U->replaceAllUsesWith(Builder.getFalse());
881       Changed = true;
882     } else
883       continue;
884 
885     if (U->use_empty()) {
886       auto *I = cast<Instruction>(U);
887       ToRemove.push_back(I);
888       I->setOperand(0, PoisonValue::get(II->getType()));
889       Changed = true;
890     }
891   }
892 
893   if (II->use_empty()) {
894     II->eraseFromParent();
895     Changed = true;
896   }
897   return Changed;
898 }
899 
900 static bool
901 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
902                           SmallVectorImpl<Instruction *> &ToRemove) {
903   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
904                               ConstraintInfo &Info) {
905     auto R = Info.getConstraintForSolving(Pred, A, B);
906     if (R.size() < 2 || !R.isValid(Info))
907       return false;
908 
909     auto &CSToUse = Info.getCS(R.IsSigned);
910     return CSToUse.isConditionImplied(R.Coefficients);
911   };
912 
913   bool Changed = false;
914   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
915     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
916     // can be simplified to a regular sub.
917     Value *A = II->getArgOperand(0);
918     Value *B = II->getArgOperand(1);
919     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
920         !DoesConditionHold(CmpInst::ICMP_SGE, B,
921                            ConstantInt::get(A->getType(), 0), Info))
922       return false;
923     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
924   }
925   return Changed;
926 }
927 
928 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
929   bool Changed = false;
930   DT.updateDFSNumbers();
931 
932   ConstraintInfo Info(F.getParent()->getDataLayout());
933   State S(DT);
934 
935   // First, collect conditions implied by branches and blocks with their
936   // Dominator DFS in and out numbers.
937   for (BasicBlock &BB : F) {
938     if (!DT.getNode(&BB))
939       continue;
940     S.addInfoFor(BB);
941   }
942 
943   // Next, sort worklist by dominance, so that dominating blocks and conditions
944   // come before blocks and conditions dominated by them. If a block and a
945   // condition have the same numbers, the condition comes before the block, as
946   // it holds on entry to the block. Also make sure conditions with constant
947   // operands come before conditions without constant operands. This increases
948   // the effectiveness of the current signed <-> unsigned fact transfer logic.
949   stable_sort(
950       S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
951         auto HasNoConstOp = [](const ConstraintOrBlock &B) {
952           return !B.IsBlock && !isa<ConstantInt>(B.Condition->getOperand(0)) &&
953                  !isa<ConstantInt>(B.Condition->getOperand(1));
954         };
955         bool NoConstOpA = HasNoConstOp(A);
956         bool NoConstOpB = HasNoConstOp(B);
957         return std::tie(A.NumIn, A.IsBlock, NoConstOpA) <
958                std::tie(B.NumIn, B.IsBlock, NoConstOpB);
959       });
960 
961   SmallVector<Instruction *> ToRemove;
962 
963   // Finally, process ordered worklist and eliminate implied conditions.
964   SmallVector<StackEntry, 16> DFSInStack;
965   for (ConstraintOrBlock &CB : S.WorkList) {
966     // First, pop entries from the stack that are out-of-scope for CB. Remove
967     // the corresponding entry from the constraint system.
968     while (!DFSInStack.empty()) {
969       auto &E = DFSInStack.back();
970       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
971                         << "\n");
972       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
973       assert(E.NumIn <= CB.NumIn);
974       if (CB.NumOut <= E.NumOut)
975         break;
976       LLVM_DEBUG({
977         dbgs() << "Removing ";
978         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
979                       Info.getValue2Index(E.IsSigned));
980         dbgs() << "\n";
981       });
982 
983       Info.popLastConstraint(E.IsSigned);
984       // Remove variables in the system that went out of scope.
985       auto &Mapping = Info.getValue2Index(E.IsSigned);
986       for (Value *V : E.ValuesToRelease)
987         Mapping.erase(V);
988       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
989       DFSInStack.pop_back();
990     }
991 
992     LLVM_DEBUG({
993       dbgs() << "Processing ";
994       if (CB.IsBlock)
995         dbgs() << *CB.BB;
996       else
997         dbgs() << *CB.Condition;
998       dbgs() << "\n";
999     });
1000 
1001     // For a block, check if any CmpInsts become known based on the current set
1002     // of constraints.
1003     if (CB.IsBlock) {
1004       for (Instruction &I : make_early_inc_range(*CB.BB)) {
1005         if (auto *II = dyn_cast<WithOverflowInst>(&I)) {
1006           Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1007           continue;
1008         }
1009         auto *Cmp = dyn_cast<ICmpInst>(&I);
1010         if (!Cmp)
1011           continue;
1012 
1013         Changed |= checkAndReplaceCondition(Cmp, Info);
1014       }
1015       continue;
1016     }
1017 
1018     ICmpInst::Predicate Pred;
1019     Value *A, *B;
1020     if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1021       // Use the inverse predicate if required.
1022       if (CB.Not)
1023         Pred = CmpInst::getInversePredicate(Pred);
1024 
1025       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1026       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1027     }
1028   }
1029 
1030 #ifndef NDEBUG
1031   unsigned SignedEntries =
1032       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1033   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1034          "updates to CS and DFSInStack are out of sync");
1035   assert(Info.getCS(true).size() == SignedEntries &&
1036          "updates to CS and DFSInStack are out of sync");
1037 #endif
1038 
1039   for (Instruction *I : ToRemove)
1040     I->eraseFromParent();
1041   return Changed;
1042 }
1043 
1044 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1045                                                  FunctionAnalysisManager &AM) {
1046   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1047   if (!eliminateConstraints(F, DT))
1048     return PreservedAnalyses::all();
1049 
1050   PreservedAnalyses PA;
1051   PA.preserve<DominatorTreeAnalysis>();
1052   PA.preserveSet<CFGAnalyses>();
1053   return PA;
1054 }
1055 
1056 namespace {
1057 
1058 class ConstraintElimination : public FunctionPass {
1059 public:
1060   static char ID;
1061 
1062   ConstraintElimination() : FunctionPass(ID) {
1063     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
1064   }
1065 
1066   bool runOnFunction(Function &F) override {
1067     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1068     return eliminateConstraints(F, DT);
1069   }
1070 
1071   void getAnalysisUsage(AnalysisUsage &AU) const override {
1072     AU.setPreservesCFG();
1073     AU.addRequired<DominatorTreeWrapperPass>();
1074     AU.addPreserved<GlobalsAAWrapperPass>();
1075     AU.addPreserved<DominatorTreeWrapperPass>();
1076   }
1077 };
1078 
1079 } // end anonymous namespace
1080 
1081 char ConstraintElimination::ID = 0;
1082 
1083 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
1084                       "Constraint Elimination", false, false)
1085 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1086 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1087 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
1088                     "Constraint Elimination", false, false)
1089 
1090 FunctionPass *llvm::createConstraintEliminationPass() {
1091   return new ConstraintElimination();
1092 }
1093