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