xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 9eda78107c4d9baca947b7bd9e0ce1c72474a59b)
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   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 IsKnownPositive = false;
332   if (match(V, m_ZExt(m_Value(Op0)))) {
333     IsKnownPositive = 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, IsKnownPositive};
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   // Only ULE and ULT predicates are supported at the moment.
417   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
418       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
419     return {};
420 
421   SmallVector<PreconditionTy, 4> Preconditions;
422   bool IsSigned = CmpInst::isSigned(Pred);
423   auto &Value2Index = getValue2Index(IsSigned);
424   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
425                         Preconditions, IsSigned, DL);
426   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
427                         Preconditions, IsSigned, DL);
428   int64_t Offset1 = ADec.Offset;
429   int64_t Offset2 = BDec.Offset;
430   Offset1 *= -1;
431 
432   auto &VariablesA = ADec.Vars;
433   auto &VariablesB = BDec.Vars;
434 
435   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
436   // new entry to NewVariables.
437   DenseMap<Value *, unsigned> NewIndexMap;
438   auto GetOrAddIndex = [&Value2Index, &NewVariables,
439                         &NewIndexMap](Value *V) -> unsigned {
440     auto V2I = Value2Index.find(V);
441     if (V2I != Value2Index.end())
442       return V2I->second;
443     auto Insert =
444         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
445     if (Insert.second)
446       NewVariables.push_back(V);
447     return Insert.first->second;
448   };
449 
450   // Make sure all variables have entries in Value2Index or NewVariables.
451   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
452     GetOrAddIndex(KV.Variable);
453 
454   // Build result constraint, by first adding all coefficients from A and then
455   // subtracting all coefficients from B.
456   ConstraintTy Res(
457       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
458       IsSigned);
459   // Collect variables that are known to be positive in all uses in the
460   // constraint.
461   DenseMap<Value *, bool> KnownPositiveVariables;
462   Res.IsEq = IsEq;
463   auto &R = Res.Coefficients;
464   for (const auto &KV : VariablesA) {
465     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
466     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
467     I.first->second &= KV.IsKnownPositive;
468   }
469 
470   for (const auto &KV : VariablesB) {
471     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
472     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
473     I.first->second &= KV.IsKnownPositive;
474   }
475 
476   int64_t OffsetSum;
477   if (AddOverflow(Offset1, Offset2, OffsetSum))
478     return {};
479   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
480     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
481       return {};
482   R[0] = OffsetSum;
483   Res.Preconditions = std::move(Preconditions);
484 
485   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
486   // variables.
487   while (!NewVariables.empty()) {
488     int64_t Last = R.back();
489     if (Last != 0)
490       break;
491     R.pop_back();
492     Value *RemovedV = NewVariables.pop_back_val();
493     NewIndexMap.erase(RemovedV);
494   }
495 
496   // Add extra constraints for variables that are known positive.
497   for (auto &KV : KnownPositiveVariables) {
498     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
499                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
500       continue;
501     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
502     C[GetOrAddIndex(KV.first)] = -1;
503     Res.ExtraInfo.push_back(C);
504   }
505   return Res;
506 }
507 
508 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
509                                                      Value *Op0,
510                                                      Value *Op1) const {
511   // If both operands are known to be non-negative, change signed predicates to
512   // unsigned ones. This increases the reasoning effectiveness in combination
513   // with the signed <-> unsigned transfer logic.
514   if (CmpInst::isSigned(Pred) &&
515       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
516       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
517     Pred = CmpInst::getUnsignedPredicate(Pred);
518 
519   SmallVector<Value *> NewVariables;
520   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
521   if (R.IsEq || !NewVariables.empty())
522     return {};
523   return R;
524 }
525 
526 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
527   return Coefficients.size() > 0 &&
528          all_of(Preconditions, [&Info](const PreconditionTy &C) {
529            return Info.doesHold(C.Pred, C.Op0, C.Op1);
530          });
531 }
532 
533 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
534                               Value *B) const {
535   auto R = getConstraintForSolving(Pred, A, B);
536   return R.Preconditions.empty() && !R.empty() &&
537          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
538 }
539 
540 void ConstraintInfo::transferToOtherSystem(
541     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
542     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
543   // Check if we can combine facts from the signed and unsigned systems to
544   // derive additional facts.
545   if (!A->getType()->isIntegerTy())
546     return;
547   // FIXME: This currently depends on the order we add facts. Ideally we
548   // would first add all known facts and only then try to add additional
549   // facts.
550   switch (Pred) {
551   default:
552     break;
553   case CmpInst::ICMP_ULT:
554     //  If B is a signed positive constant, A >=s 0 and A <s B.
555     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
556       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
557               NumOut, DFSInStack);
558       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
559     }
560     break;
561   case CmpInst::ICMP_SLT:
562     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
563       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
564     break;
565   case CmpInst::ICMP_SGT:
566     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
567       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
568               NumOut, DFSInStack);
569     break;
570   case CmpInst::ICMP_SGE:
571     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
572       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
573     }
574     break;
575   }
576 }
577 
578 namespace {
579 /// Represents either
580 ///  * a condition that holds on entry to a block (=conditional fact)
581 ///  * an assume (=assume fact)
582 ///  * an instruction to simplify.
583 /// It also tracks the Dominator DFS in and out numbers for each entry.
584 struct FactOrCheck {
585   Instruction *Inst;
586   unsigned NumIn;
587   unsigned NumOut;
588   bool IsCheck;
589   bool Not;
590 
591   FactOrCheck(DomTreeNode *DTN, Instruction *Inst, bool IsCheck, bool Not)
592       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
593         IsCheck(IsCheck), Not(Not) {}
594 
595   static FactOrCheck getFact(DomTreeNode *DTN, Instruction *Inst,
596                              bool Not = false) {
597     return FactOrCheck(DTN, Inst, false, Not);
598   }
599 
600   static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *Inst) {
601     return FactOrCheck(DTN, Inst, true, false);
602   }
603 
604   bool isAssumeFact() const {
605     if (!IsCheck && isa<IntrinsicInst>(Inst)) {
606       assert(match(Inst, m_Intrinsic<Intrinsic::assume>()));
607       return true;
608     }
609     return false;
610   }
611 
612   bool isConditionFact() const { return !IsCheck && isa<CmpInst>(Inst); }
613 };
614 
615 /// Keep state required to build worklist.
616 struct State {
617   DominatorTree &DT;
618   SmallVector<FactOrCheck, 64> WorkList;
619 
620   State(DominatorTree &DT) : DT(DT) {}
621 
622   /// Process block \p BB and add known facts to work-list.
623   void addInfoFor(BasicBlock &BB);
624 
625   /// Returns true if we can add a known condition from BB to its successor
626   /// block Succ. Each predecessor of Succ can either be BB or be dominated
627   /// by Succ (e.g. the case when adding a condition from a pre-header to a
628   /// loop header).
629   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
630     if (BB.getSingleSuccessor()) {
631       assert(BB.getSingleSuccessor() == Succ);
632       return DT.properlyDominates(&BB, Succ);
633     }
634     return any_of(successors(&BB),
635                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
636            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
637              return Pred == &BB || DT.dominates(Succ, Pred);
638            });
639   }
640 };
641 
642 } // namespace
643 
644 #ifndef NDEBUG
645 static void dumpWithNames(const ConstraintSystem &CS,
646                           DenseMap<Value *, unsigned> &Value2Index) {
647   SmallVector<std::string> Names(Value2Index.size(), "");
648   for (auto &KV : Value2Index) {
649     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
650   }
651   CS.dump(Names);
652 }
653 
654 static void dumpWithNames(ArrayRef<int64_t> C,
655                           DenseMap<Value *, unsigned> &Value2Index) {
656   ConstraintSystem CS;
657   CS.addVariableRowFill(C);
658   dumpWithNames(CS, Value2Index);
659 }
660 #endif
661 
662 void State::addInfoFor(BasicBlock &BB) {
663   // True as long as long as the current instruction is guaranteed to execute.
664   bool GuaranteedToExecute = true;
665   // Queue conditions and assumes.
666   for (Instruction &I : BB) {
667     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
668       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), Cmp));
669       continue;
670     }
671 
672     if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) {
673       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), &I));
674       continue;
675     }
676 
677     Value *Cond;
678     // For now, just handle assumes with a single compare as condition.
679     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
680         isa<ICmpInst>(Cond)) {
681       if (GuaranteedToExecute) {
682         // The assume is guaranteed to execute when BB is entered, hence Cond
683         // holds on entry to BB.
684         WorkList.emplace_back(FactOrCheck::getFact(DT.getNode(I.getParent()),
685                                                    cast<Instruction>(Cond)));
686       } else {
687         WorkList.emplace_back(
688             FactOrCheck::getFact(DT.getNode(I.getParent()), &I));
689       }
690     }
691     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
692   }
693 
694   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
695   if (!Br || !Br->isConditional())
696     return;
697 
698   Value *Cond = Br->getCondition();
699 
700   // If the condition is a chain of ORs/AND and the successor only has the
701   // current block as predecessor, queue conditions for the successor.
702   Value *Op0, *Op1;
703   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
704       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
705     bool IsOr = match(Cond, m_LogicalOr());
706     bool IsAnd = match(Cond, m_LogicalAnd());
707     // If there's a select that matches both AND and OR, we need to commit to
708     // one of the options. Arbitrarily pick OR.
709     if (IsOr && IsAnd)
710       IsAnd = false;
711 
712     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
713     if (canAddSuccessor(BB, Successor)) {
714       SmallVector<Value *> CondWorkList;
715       SmallPtrSet<Value *, 8> SeenCond;
716       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
717         if (SeenCond.insert(V).second)
718           CondWorkList.push_back(V);
719       };
720       QueueValue(Op1);
721       QueueValue(Op0);
722       while (!CondWorkList.empty()) {
723         Value *Cur = CondWorkList.pop_back_val();
724         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
725           WorkList.emplace_back(
726               FactOrCheck::getFact(DT.getNode(Successor), Cmp, IsOr));
727           continue;
728         }
729         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
730           QueueValue(Op1);
731           QueueValue(Op0);
732           continue;
733         }
734         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
735           QueueValue(Op1);
736           QueueValue(Op0);
737           continue;
738         }
739       }
740     }
741     return;
742   }
743 
744   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
745   if (!CmpI)
746     return;
747   if (canAddSuccessor(BB, Br->getSuccessor(0)))
748     WorkList.emplace_back(
749         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(0)), CmpI));
750   if (canAddSuccessor(BB, Br->getSuccessor(1)))
751     WorkList.emplace_back(
752         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(1)), CmpI, true));
753 }
754 
755 static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info) {
756   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
757 
758   CmpInst::Predicate Pred = Cmp->getPredicate();
759   Value *A = Cmp->getOperand(0);
760   Value *B = Cmp->getOperand(1);
761 
762   auto R = Info.getConstraintForSolving(Pred, A, B);
763   if (R.empty() || !R.isValid(Info)){
764     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
765     return false;
766   }
767 
768   auto &CSToUse = Info.getCS(R.IsSigned);
769 
770   // If there was extra information collected during decomposition, apply
771   // it now and remove it immediately once we are done with reasoning
772   // about the constraint.
773   for (auto &Row : R.ExtraInfo)
774     CSToUse.addVariableRow(Row);
775   auto InfoRestorer = make_scope_exit([&]() {
776     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
777       CSToUse.popLastConstraint();
778   });
779 
780   bool Changed = false;
781   if (CSToUse.isConditionImplied(R.Coefficients)) {
782     if (!DebugCounter::shouldExecute(EliminatedCounter))
783       return false;
784 
785     LLVM_DEBUG({
786       dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n";
787       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
788     });
789     Constant *TrueC =
790         ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType()));
791     Cmp->replaceUsesWithIf(TrueC, [](Use &U) {
792       // Conditions in an assume trivially simplify to true. Skip uses
793       // in assume calls to not destroy the available information.
794       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
795       return !II || II->getIntrinsicID() != Intrinsic::assume;
796     });
797     NumCondsRemoved++;
798     Changed = true;
799   }
800   if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) {
801     if (!DebugCounter::shouldExecute(EliminatedCounter))
802       return false;
803 
804     LLVM_DEBUG({
805       dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n";
806       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
807     });
808     Constant *FalseC =
809         ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType()));
810     Cmp->replaceAllUsesWith(FalseC);
811     NumCondsRemoved++;
812     Changed = true;
813   }
814   return Changed;
815 }
816 
817 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
818                              unsigned NumIn, unsigned NumOut,
819                              SmallVectorImpl<StackEntry> &DFSInStack) {
820   // If the constraint has a pre-condition, skip the constraint if it does not
821   // hold.
822   SmallVector<Value *> NewVariables;
823   auto R = getConstraint(Pred, A, B, NewVariables);
824   if (!R.isValid(*this))
825     return;
826 
827   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
828              A->printAsOperand(dbgs(), false); dbgs() << ", ";
829              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
830   bool Added = false;
831   auto &CSToUse = getCS(R.IsSigned);
832   if (R.Coefficients.empty())
833     return;
834 
835   Added |= CSToUse.addVariableRowFill(R.Coefficients);
836 
837   // If R has been added to the system, add the new variables and queue it for
838   // removal once it goes out-of-scope.
839   if (Added) {
840     SmallVector<Value *, 2> ValuesToRelease;
841     auto &Value2Index = getValue2Index(R.IsSigned);
842     for (Value *V : NewVariables) {
843       Value2Index.insert({V, Value2Index.size() + 1});
844       ValuesToRelease.push_back(V);
845     }
846 
847     LLVM_DEBUG({
848       dbgs() << "  constraint: ";
849       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
850       dbgs() << "\n";
851     });
852 
853     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease);
854 
855     if (R.IsEq) {
856       // Also add the inverted constraint for equality constraints.
857       for (auto &Coeff : R.Coefficients)
858         Coeff *= -1;
859       CSToUse.addVariableRowFill(R.Coefficients);
860 
861       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
862                               SmallVector<Value *, 2>());
863     }
864   }
865 }
866 
867 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
868                                    SmallVectorImpl<Instruction *> &ToRemove) {
869   bool Changed = false;
870   IRBuilder<> Builder(II->getParent(), II->getIterator());
871   Value *Sub = nullptr;
872   for (User *U : make_early_inc_range(II->users())) {
873     if (match(U, m_ExtractValue<0>(m_Value()))) {
874       if (!Sub)
875         Sub = Builder.CreateSub(A, B);
876       U->replaceAllUsesWith(Sub);
877       Changed = true;
878     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
879       U->replaceAllUsesWith(Builder.getFalse());
880       Changed = true;
881     } else
882       continue;
883 
884     if (U->use_empty()) {
885       auto *I = cast<Instruction>(U);
886       ToRemove.push_back(I);
887       I->setOperand(0, PoisonValue::get(II->getType()));
888       Changed = true;
889     }
890   }
891 
892   if (II->use_empty()) {
893     II->eraseFromParent();
894     Changed = true;
895   }
896   return Changed;
897 }
898 
899 static bool
900 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
901                           SmallVectorImpl<Instruction *> &ToRemove) {
902   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
903                               ConstraintInfo &Info) {
904     auto R = Info.getConstraintForSolving(Pred, A, B);
905     if (R.size() < 2 || !R.isValid(Info))
906       return false;
907 
908     auto &CSToUse = Info.getCS(R.IsSigned);
909     return CSToUse.isConditionImplied(R.Coefficients);
910   };
911 
912   bool Changed = false;
913   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
914     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
915     // can be simplified to a regular sub.
916     Value *A = II->getArgOperand(0);
917     Value *B = II->getArgOperand(1);
918     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
919         !DoesConditionHold(CmpInst::ICMP_SGE, B,
920                            ConstantInt::get(A->getType(), 0), Info))
921       return false;
922     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
923   }
924   return Changed;
925 }
926 
927 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
928   bool Changed = false;
929   DT.updateDFSNumbers();
930 
931   ConstraintInfo Info(F.getParent()->getDataLayout());
932   State S(DT);
933 
934   // First, collect conditions implied by branches and blocks with their
935   // Dominator DFS in and out numbers.
936   for (BasicBlock &BB : F) {
937     if (!DT.getNode(&BB))
938       continue;
939     S.addInfoFor(BB);
940   }
941 
942   // Next, sort worklist by dominance, so that dominating conditions to check
943   // and facts come before conditions and facts dominated by them. If a
944   // condition to check and a fact have the same numbers, conditional facts come
945   // first. Assume facts and checks are ordered according to their relative
946   // order in the containing basic block. Also make sure conditions with
947   // constant operands come before conditions without constant operands. This
948   // increases the effectiveness of the current signed <-> unsigned fact
949   // transfer logic.
950   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
951     auto HasNoConstOp = [](const FactOrCheck &B) {
952       return !isa<ConstantInt>(B.Inst->getOperand(0)) &&
953              !isa<ConstantInt>(B.Inst->getOperand(1));
954     };
955     // If both entries have the same In numbers, conditional facts come first.
956     // Otherwise use the relative order in the basic block.
957     if (A.NumIn == B.NumIn) {
958       if (A.isConditionFact() && B.isConditionFact()) {
959         bool NoConstOpA = HasNoConstOp(A);
960         bool NoConstOpB = HasNoConstOp(B);
961         return NoConstOpA < NoConstOpB;
962       }
963       if (A.isConditionFact())
964         return true;
965       if (B.isConditionFact())
966         return false;
967       return A.Inst->comesBefore(B.Inst);
968     }
969     return A.NumIn < B.NumIn;
970   });
971 
972   SmallVector<Instruction *> ToRemove;
973 
974   // Finally, process ordered worklist and eliminate implied conditions.
975   SmallVector<StackEntry, 16> DFSInStack;
976   for (FactOrCheck &CB : S.WorkList) {
977     // First, pop entries from the stack that are out-of-scope for CB. Remove
978     // the corresponding entry from the constraint system.
979     while (!DFSInStack.empty()) {
980       auto &E = DFSInStack.back();
981       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
982                         << "\n");
983       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
984       assert(E.NumIn <= CB.NumIn);
985       if (CB.NumOut <= E.NumOut)
986         break;
987       LLVM_DEBUG({
988         dbgs() << "Removing ";
989         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
990                       Info.getValue2Index(E.IsSigned));
991         dbgs() << "\n";
992       });
993 
994       Info.popLastConstraint(E.IsSigned);
995       // Remove variables in the system that went out of scope.
996       auto &Mapping = Info.getValue2Index(E.IsSigned);
997       for (Value *V : E.ValuesToRelease)
998         Mapping.erase(V);
999       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1000       DFSInStack.pop_back();
1001     }
1002 
1003     LLVM_DEBUG({
1004       dbgs() << "Processing ";
1005       if (CB.IsCheck)
1006         dbgs() << "condition to simplify: " << *CB.Inst;
1007       else
1008         dbgs() << "fact to add to the system: " << *CB.Inst;
1009       dbgs() << "\n";
1010     });
1011 
1012     // For a block, check if any CmpInsts become known based on the current set
1013     // of constraints.
1014     if (CB.IsCheck) {
1015       if (auto *II = dyn_cast<WithOverflowInst>(CB.Inst)) {
1016         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1017       } else if (auto *Cmp = dyn_cast<ICmpInst>(CB.Inst)) {
1018         Changed |= checkAndReplaceCondition(Cmp, Info);
1019       }
1020       continue;
1021     }
1022 
1023     ICmpInst::Predicate Pred;
1024     Value *A, *B;
1025     Value *Cmp = CB.Inst;
1026     match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp)));
1027     if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1028       // Use the inverse predicate if required.
1029       if (CB.Not)
1030         Pred = CmpInst::getInversePredicate(Pred);
1031 
1032       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1033       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1034     }
1035   }
1036 
1037 #ifndef NDEBUG
1038   unsigned SignedEntries =
1039       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1040   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1041          "updates to CS and DFSInStack are out of sync");
1042   assert(Info.getCS(true).size() == SignedEntries &&
1043          "updates to CS and DFSInStack are out of sync");
1044 #endif
1045 
1046   for (Instruction *I : ToRemove)
1047     I->eraseFromParent();
1048   return Changed;
1049 }
1050 
1051 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1052                                                  FunctionAnalysisManager &AM) {
1053   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1054   if (!eliminateConstraints(F, DT))
1055     return PreservedAnalyses::all();
1056 
1057   PreservedAnalyses PA;
1058   PA.preserve<DominatorTreeAnalysis>();
1059   PA.preserveSet<CFGAnalyses>();
1060   return PA;
1061 }
1062 
1063 namespace {
1064 
1065 class ConstraintElimination : public FunctionPass {
1066 public:
1067   static char ID;
1068 
1069   ConstraintElimination() : FunctionPass(ID) {
1070     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
1071   }
1072 
1073   bool runOnFunction(Function &F) override {
1074     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1075     return eliminateConstraints(F, DT);
1076   }
1077 
1078   void getAnalysisUsage(AnalysisUsage &AU) const override {
1079     AU.setPreservesCFG();
1080     AU.addRequired<DominatorTreeWrapperPass>();
1081     AU.addPreserved<GlobalsAAWrapperPass>();
1082     AU.addPreserved<DominatorTreeWrapperPass>();
1083   }
1084 };
1085 
1086 } // end anonymous namespace
1087 
1088 char ConstraintElimination::ID = 0;
1089 
1090 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
1091                       "Constraint Elimination", false, false)
1092 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1093 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1094 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
1095                     "Constraint Elimination", false, false)
1096 
1097 FunctionPass *llvm::createConstraintEliminationPass() {
1098   return new ConstraintElimination();
1099 }
1100