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