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