xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 1d23d60c8d0406b9163d223d2721c5e4f1932f50)
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     break;
590   case CmpInst::ICMP_SGE:
591     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
592       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
593     }
594     break;
595   }
596 }
597 
598 namespace {
599 /// Represents either
600 ///  * a condition that holds on entry to a block (=conditional fact)
601 ///  * an assume (=assume fact)
602 ///  * an instruction to simplify.
603 /// It also tracks the Dominator DFS in and out numbers for each entry.
604 struct FactOrCheck {
605   Instruction *Inst;
606   unsigned NumIn;
607   unsigned NumOut;
608   bool IsCheck;
609   bool Not;
610 
611   FactOrCheck(DomTreeNode *DTN, Instruction *Inst, bool IsCheck, bool Not)
612       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
613         IsCheck(IsCheck), Not(Not) {}
614 
615   static FactOrCheck getFact(DomTreeNode *DTN, Instruction *Inst,
616                              bool Not = false) {
617     return FactOrCheck(DTN, Inst, false, Not);
618   }
619 
620   static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *Inst) {
621     return FactOrCheck(DTN, Inst, true, false);
622   }
623 
624   bool isAssumeFact() const {
625     if (!IsCheck && isa<IntrinsicInst>(Inst)) {
626       assert(match(Inst, m_Intrinsic<Intrinsic::assume>()));
627       return true;
628     }
629     return false;
630   }
631 
632   bool isConditionFact() const { return !IsCheck && isa<CmpInst>(Inst); }
633 };
634 
635 /// Keep state required to build worklist.
636 struct State {
637   DominatorTree &DT;
638   SmallVector<FactOrCheck, 64> WorkList;
639 
640   State(DominatorTree &DT) : DT(DT) {}
641 
642   /// Process block \p BB and add known facts to work-list.
643   void addInfoFor(BasicBlock &BB);
644 
645   /// Returns true if we can add a known condition from BB to its successor
646   /// block Succ.
647   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
648     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
649   }
650 };
651 
652 } // namespace
653 
654 #ifndef NDEBUG
655 
656 static void dumpConstraint(ArrayRef<int64_t> C,
657                            const DenseMap<Value *, unsigned> &Value2Index) {
658   ConstraintSystem CS(Value2Index);
659   CS.addVariableRowFill(C);
660   CS.dump();
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.contains(V) || !I ||
811           !isa<CmpInst, BinaryOperator, GEPOperator, 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.contains(V) && 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       CSToUse.dump();
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       CSToUse.dump();
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 '" << 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       dumpConstraint(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   SmallVector<Value *> FunctionArgs;
1092   for (Value &Arg : F.args())
1093     FunctionArgs.push_back(&Arg);
1094   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
1095   State S(DT);
1096   std::unique_ptr<Module> ReproducerModule(
1097       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1098 
1099   // First, collect conditions implied by branches and blocks with their
1100   // Dominator DFS in and out numbers.
1101   for (BasicBlock &BB : F) {
1102     if (!DT.getNode(&BB))
1103       continue;
1104     S.addInfoFor(BB);
1105   }
1106 
1107   // Next, sort worklist by dominance, so that dominating conditions to check
1108   // and facts come before conditions and facts dominated by them. If a
1109   // condition to check and a fact have the same numbers, conditional facts come
1110   // first. Assume facts and checks are ordered according to their relative
1111   // order in the containing basic block. Also make sure conditions with
1112   // constant operands come before conditions without constant operands. This
1113   // increases the effectiveness of the current signed <-> unsigned fact
1114   // transfer logic.
1115   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1116     auto HasNoConstOp = [](const FactOrCheck &B) {
1117       return !isa<ConstantInt>(B.Inst->getOperand(0)) &&
1118              !isa<ConstantInt>(B.Inst->getOperand(1));
1119     };
1120     // If both entries have the same In numbers, conditional facts come first.
1121     // Otherwise use the relative order in the basic block.
1122     if (A.NumIn == B.NumIn) {
1123       if (A.isConditionFact() && B.isConditionFact()) {
1124         bool NoConstOpA = HasNoConstOp(A);
1125         bool NoConstOpB = HasNoConstOp(B);
1126         return NoConstOpA < NoConstOpB;
1127       }
1128       if (A.isConditionFact())
1129         return true;
1130       if (B.isConditionFact())
1131         return false;
1132       return A.Inst->comesBefore(B.Inst);
1133     }
1134     return A.NumIn < B.NumIn;
1135   });
1136 
1137   SmallVector<Instruction *> ToRemove;
1138 
1139   // Finally, process ordered worklist and eliminate implied conditions.
1140   SmallVector<StackEntry, 16> DFSInStack;
1141   SmallVector<ReproducerEntry> ReproducerCondStack;
1142   for (FactOrCheck &CB : S.WorkList) {
1143     // First, pop entries from the stack that are out-of-scope for CB. Remove
1144     // the corresponding entry from the constraint system.
1145     while (!DFSInStack.empty()) {
1146       auto &E = DFSInStack.back();
1147       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1148                         << "\n");
1149       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1150       assert(E.NumIn <= CB.NumIn);
1151       if (CB.NumOut <= E.NumOut)
1152         break;
1153       LLVM_DEBUG({
1154         dbgs() << "Removing ";
1155         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1156                        Info.getValue2Index(E.IsSigned));
1157         dbgs() << "\n";
1158       });
1159 
1160       Info.popLastConstraint(E.IsSigned);
1161       // Remove variables in the system that went out of scope.
1162       auto &Mapping = Info.getValue2Index(E.IsSigned);
1163       for (Value *V : E.ValuesToRelease)
1164         Mapping.erase(V);
1165       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1166       DFSInStack.pop_back();
1167       if (ReproducerModule)
1168         ReproducerCondStack.pop_back();
1169     }
1170 
1171     LLVM_DEBUG({
1172       dbgs() << "Processing ";
1173       if (CB.IsCheck)
1174         dbgs() << "condition to simplify: " << *CB.Inst;
1175       else
1176         dbgs() << "fact to add to the system: " << *CB.Inst;
1177       dbgs() << "\n";
1178     });
1179 
1180     // For a block, check if any CmpInsts become known based on the current set
1181     // of constraints.
1182     if (CB.IsCheck) {
1183       if (auto *II = dyn_cast<WithOverflowInst>(CB.Inst)) {
1184         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1185       } else if (auto *Cmp = dyn_cast<ICmpInst>(CB.Inst)) {
1186         Changed |= checkAndReplaceCondition(Cmp, Info, ReproducerModule.get(),
1187                                             ReproducerCondStack, S.DT);
1188       }
1189       continue;
1190     }
1191 
1192     ICmpInst::Predicate Pred;
1193     Value *A, *B;
1194     Value *Cmp = CB.Inst;
1195     match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp)));
1196     if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1197       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1198         LLVM_DEBUG(
1199             dbgs()
1200             << "Skip adding constraint because system has too many rows.\n");
1201         continue;
1202       }
1203 
1204       // Use the inverse predicate if required.
1205       if (CB.Not)
1206         Pred = CmpInst::getInversePredicate(Pred);
1207 
1208       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1209       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1210         ReproducerCondStack.emplace_back(cast<CmpInst>(Cmp), CB.Not);
1211 
1212       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1213       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1214         // Add dummy entries to ReproducerCondStack to keep it in sync with
1215         // DFSInStack.
1216         for (unsigned I = 0,
1217                       E = (DFSInStack.size() - ReproducerCondStack.size());
1218              I < E; ++I) {
1219           ReproducerCondStack.emplace_back(nullptr, false);
1220         }
1221       }
1222     }
1223   }
1224 
1225   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1226     std::string S;
1227     raw_string_ostream StringS(S);
1228     ReproducerModule->print(StringS, nullptr);
1229     StringS.flush();
1230     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1231     Rem << ore::NV("module") << S;
1232     ORE.emit(Rem);
1233   }
1234 
1235 #ifndef NDEBUG
1236   unsigned SignedEntries =
1237       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1238   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1239          "updates to CS and DFSInStack are out of sync");
1240   assert(Info.getCS(true).size() == SignedEntries &&
1241          "updates to CS and DFSInStack are out of sync");
1242 #endif
1243 
1244   for (Instruction *I : ToRemove)
1245     I->eraseFromParent();
1246   return Changed;
1247 }
1248 
1249 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1250                                                  FunctionAnalysisManager &AM) {
1251   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1252   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1253   if (!eliminateConstraints(F, DT, ORE))
1254     return PreservedAnalyses::all();
1255 
1256   PreservedAnalyses PA;
1257   PA.preserve<DominatorTreeAnalysis>();
1258   PA.preserveSet<CFGAnalyses>();
1259   return PA;
1260 }
1261