xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 56a3e49a00161f6ac71316e3c1f4d5069c916590)
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/LoopInfo.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/DebugCounter.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
43 
44 #include <cmath>
45 #include <optional>
46 #include <string>
47 
48 using namespace llvm;
49 using namespace PatternMatch;
50 
51 #define DEBUG_TYPE "constraint-elimination"
52 
53 STATISTIC(NumCondsRemoved, "Number of instructions removed");
54 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
55               "Controls which conditions are eliminated");
56 
57 static cl::opt<unsigned>
58     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
59             cl::desc("Maximum number of rows to keep in constraint system"));
60 
61 static cl::opt<bool> DumpReproducers(
62     "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
63     cl::desc("Dump IR to reproduce successful transformations."));
64 
65 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
66 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
67 
68 // A helper to multiply 2 signed integers where overflowing is allowed.
69 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
70   int64_t Result;
71   MulOverflow(A, B, Result);
72   return Result;
73 }
74 
75 // A helper to add 2 signed integers where overflowing is allowed.
76 static int64_t addWithOverflow(int64_t A, int64_t B) {
77   int64_t Result;
78   AddOverflow(A, B, Result);
79   return Result;
80 }
81 
82 static Instruction *getContextInstForUse(Use &U) {
83   Instruction *UserI = cast<Instruction>(U.getUser());
84   if (auto *Phi = dyn_cast<PHINode>(UserI))
85     UserI = Phi->getIncomingBlock(U)->getTerminator();
86   return UserI;
87 }
88 
89 namespace {
90 /// Struct to express a condition of the form %Op0 Pred %Op1.
91 struct ConditionTy {
92   CmpInst::Predicate Pred;
93   Value *Op0;
94   Value *Op1;
95 
96   ConditionTy()
97       : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {}
98   ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
99       : Pred(Pred), Op0(Op0), Op1(Op1) {}
100 };
101 
102 /// Represents either
103 ///  * a condition that holds on entry to a block (=condition fact)
104 ///  * an assume (=assume fact)
105 ///  * a use of a compare instruction to simplify.
106 /// It also tracks the Dominator DFS in and out numbers for each entry.
107 struct FactOrCheck {
108   enum class EntryTy {
109     ConditionFact, /// A condition that holds on entry to a block.
110     InstFact,      /// A fact that holds after Inst executed (e.g. an assume or
111                    /// min/mix intrinsic.
112     InstCheck,     /// An instruction to simplify (e.g. an overflow math
113                    /// intrinsics).
114     UseCheck       /// An use of a compare instruction to simplify.
115   };
116 
117   union {
118     Instruction *Inst;
119     Use *U;
120     ConditionTy Cond;
121   };
122 
123   /// A pre-condition that must hold for the current fact to be added to the
124   /// system.
125   ConditionTy DoesHold;
126 
127   unsigned NumIn;
128   unsigned NumOut;
129   EntryTy Ty;
130 
131   FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
132       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
133         Ty(Ty) {}
134 
135   FactOrCheck(DomTreeNode *DTN, Use *U)
136       : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr),
137         NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
138         Ty(EntryTy::UseCheck) {}
139 
140   FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1,
141               ConditionTy Precond = ConditionTy())
142       : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
143         NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
144 
145   static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred,
146                                       Value *Op0, Value *Op1,
147                                       ConditionTy Precond = ConditionTy()) {
148     return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
149   }
150 
151   static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
152     return FactOrCheck(EntryTy::InstFact, DTN, Inst);
153   }
154 
155   static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
156     return FactOrCheck(DTN, U);
157   }
158 
159   static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
160     return FactOrCheck(EntryTy::InstCheck, DTN, CI);
161   }
162 
163   bool isCheck() const {
164     return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
165   }
166 
167   Instruction *getContextInst() const {
168     if (Ty == EntryTy::UseCheck)
169       return getContextInstForUse(*U);
170     return Inst;
171   }
172 
173   Instruction *getInstructionToSimplify() const {
174     assert(isCheck());
175     if (Ty == EntryTy::InstCheck)
176       return Inst;
177     // The use may have been simplified to a constant already.
178     return dyn_cast<Instruction>(*U);
179   }
180 
181   bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
182 };
183 
184 /// Keep state required to build worklist.
185 struct State {
186   DominatorTree &DT;
187   LoopInfo &LI;
188   ScalarEvolution &SE;
189   SmallVector<FactOrCheck, 64> WorkList;
190 
191   State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
192       : DT(DT), LI(LI), SE(SE) {}
193 
194   /// Process block \p BB and add known facts to work-list.
195   void addInfoFor(BasicBlock &BB);
196 
197   /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
198   /// controlling the loop header.
199   void addInfoForInductions(BasicBlock &BB);
200 
201   /// Returns true if we can add a known condition from BB to its successor
202   /// block Succ.
203   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
204     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
205   }
206 };
207 
208 class ConstraintInfo;
209 
210 struct StackEntry {
211   unsigned NumIn;
212   unsigned NumOut;
213   bool IsSigned = false;
214   /// Variables that can be removed from the system once the stack entry gets
215   /// removed.
216   SmallVector<Value *, 2> ValuesToRelease;
217 
218   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
219              SmallVector<Value *, 2> ValuesToRelease)
220       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
221         ValuesToRelease(ValuesToRelease) {}
222 };
223 
224 struct ConstraintTy {
225   SmallVector<int64_t, 8> Coefficients;
226   SmallVector<ConditionTy, 2> Preconditions;
227 
228   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
229 
230   bool IsSigned = false;
231 
232   ConstraintTy() = default;
233 
234   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
235                bool IsNe)
236       : Coefficients(Coefficients), IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {
237   }
238 
239   unsigned size() const { return Coefficients.size(); }
240 
241   unsigned empty() const { return Coefficients.empty(); }
242 
243   /// Returns true if all preconditions for this list of constraints are
244   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
245   bool isValid(const ConstraintInfo &Info) const;
246 
247   bool isEq() const { return IsEq; }
248 
249   bool isNe() const { return IsNe; }
250 
251   /// Check if the current constraint is implied by the given ConstraintSystem.
252   ///
253   /// \return true or false if the constraint is proven to be respectively true,
254   /// or false. When the constraint cannot be proven to be either true or false,
255   /// std::nullopt is returned.
256   std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
257 
258 private:
259   bool IsEq = false;
260   bool IsNe = false;
261 };
262 
263 /// Wrapper encapsulating separate constraint systems and corresponding value
264 /// mappings for both unsigned and signed information. Facts are added to and
265 /// conditions are checked against the corresponding system depending on the
266 /// signed-ness of their predicates. While the information is kept separate
267 /// based on signed-ness, certain conditions can be transferred between the two
268 /// systems.
269 class ConstraintInfo {
270 
271   ConstraintSystem UnsignedCS;
272   ConstraintSystem SignedCS;
273 
274   const DataLayout &DL;
275 
276 public:
277   ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
278       : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {}
279 
280   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
281     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
282   }
283   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
284     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
285   }
286 
287   ConstraintSystem &getCS(bool Signed) {
288     return Signed ? SignedCS : UnsignedCS;
289   }
290   const ConstraintSystem &getCS(bool Signed) const {
291     return Signed ? SignedCS : UnsignedCS;
292   }
293 
294   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
295   void popLastNVariables(bool Signed, unsigned N) {
296     getCS(Signed).popLastNVariables(N);
297   }
298 
299   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
300 
301   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
302                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
303 
304   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
305   /// constraints, using indices from the corresponding constraint system.
306   /// New variables that need to be added to the system are collected in
307   /// \p NewVariables.
308   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
309                              SmallVectorImpl<Value *> &NewVariables) const;
310 
311   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
312   /// constraints using getConstraint. Returns an empty constraint if the result
313   /// cannot be used to query the existing constraint system, e.g. because it
314   /// would require adding new variables. Also tries to convert signed
315   /// predicates to unsigned ones if possible to allow using the unsigned system
316   /// which increases the effectiveness of the signed <-> unsigned transfer
317   /// logic.
318   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
319                                        Value *Op1) const;
320 
321   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
322   /// system if \p Pred is signed/unsigned.
323   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
324                              unsigned NumIn, unsigned NumOut,
325                              SmallVectorImpl<StackEntry> &DFSInStack);
326 };
327 
328 /// Represents a (Coefficient * Variable) entry after IR decomposition.
329 struct DecompEntry {
330   int64_t Coefficient;
331   Value *Variable;
332   /// True if the variable is known positive in the current constraint.
333   bool IsKnownNonNegative;
334 
335   DecompEntry(int64_t Coefficient, Value *Variable,
336               bool IsKnownNonNegative = false)
337       : Coefficient(Coefficient), Variable(Variable),
338         IsKnownNonNegative(IsKnownNonNegative) {}
339 };
340 
341 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
342 struct Decomposition {
343   int64_t Offset = 0;
344   SmallVector<DecompEntry, 3> Vars;
345 
346   Decomposition(int64_t Offset) : Offset(Offset) {}
347   Decomposition(Value *V, bool IsKnownNonNegative = false) {
348     Vars.emplace_back(1, V, IsKnownNonNegative);
349   }
350   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
351       : Offset(Offset), Vars(Vars) {}
352 
353   void add(int64_t OtherOffset) {
354     Offset = addWithOverflow(Offset, OtherOffset);
355   }
356 
357   void add(const Decomposition &Other) {
358     add(Other.Offset);
359     append_range(Vars, Other.Vars);
360   }
361 
362   void mul(int64_t Factor) {
363     Offset = multiplyWithOverflow(Offset, Factor);
364     for (auto &Var : Vars)
365       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
366   }
367 };
368 
369 } // namespace
370 
371 static Decomposition decompose(Value *V,
372                                SmallVectorImpl<ConditionTy> &Preconditions,
373                                bool IsSigned, const DataLayout &DL);
374 
375 static bool canUseSExt(ConstantInt *CI) {
376   const APInt &Val = CI->getValue();
377   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
378 }
379 
380 static Decomposition decomposeGEP(GEPOperator &GEP,
381                                   SmallVectorImpl<ConditionTy> &Preconditions,
382                                   bool IsSigned, const DataLayout &DL) {
383   // Do not reason about pointers where the index size is larger than 64 bits,
384   // as the coefficients used to encode constraints are 64 bit integers.
385   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
386     return &GEP;
387 
388   if (!GEP.isInBounds())
389     return &GEP;
390 
391   assert(!IsSigned && "The logic below only supports decomposition for "
392                       "unsinged predicates at the moment.");
393   Type *PtrTy = GEP.getType()->getScalarType();
394   unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
395   MapVector<Value *, APInt> VariableOffsets;
396   APInt ConstantOffset(BitWidth, 0);
397   if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
398     return &GEP;
399 
400   // Handle the (gep (gep ....), C) case by incrementing the constant
401   // coefficient of the inner GEP, if C is a constant.
402   auto *InnerGEP = dyn_cast<GEPOperator>(GEP.getPointerOperand());
403   if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) {
404     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
405     Result.add(ConstantOffset.getSExtValue());
406 
407     if (ConstantOffset.isNegative()) {
408       unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType());
409       int64_t ConstantOffsetI = ConstantOffset.getSExtValue();
410       if (ConstantOffsetI % Scale != 0)
411         return &GEP;
412       // Add pre-condition ensuring the GEP is increasing monotonically and
413       // can be de-composed.
414       // Both sides are normalized by being divided by Scale.
415       Preconditions.emplace_back(
416           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
417           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
418                            -1 * (ConstantOffsetI / Scale)));
419     }
420     return Result;
421   }
422 
423   Decomposition Result(ConstantOffset.getSExtValue(),
424                        DecompEntry(1, GEP.getPointerOperand()));
425   for (auto [Index, Scale] : VariableOffsets) {
426     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
427     IdxResult.mul(Scale.getSExtValue());
428     Result.add(IdxResult);
429 
430     // If Op0 is signed non-negative, the GEP is increasing monotonically and
431     // can be de-composed.
432     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
433       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
434                                  ConstantInt::get(Index->getType(), 0));
435   }
436   return Result;
437 }
438 
439 // Decomposes \p V into a constant offset + list of pairs { Coefficient,
440 // Variable } where Coefficient * Variable. The sum of the constant offset and
441 // pairs equals \p V.
442 static Decomposition decompose(Value *V,
443                                SmallVectorImpl<ConditionTy> &Preconditions,
444                                bool IsSigned, const DataLayout &DL) {
445 
446   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
447                                                       bool IsSignedB) {
448     auto ResA = decompose(A, Preconditions, IsSigned, DL);
449     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
450     ResA.add(ResB);
451     return ResA;
452   };
453 
454   // Decompose \p V used with a signed predicate.
455   if (IsSigned) {
456     if (auto *CI = dyn_cast<ConstantInt>(V)) {
457       if (canUseSExt(CI))
458         return CI->getSExtValue();
459     }
460     Value *Op0;
461     Value *Op1;
462     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
463       return MergeResults(Op0, Op1, IsSigned);
464 
465     ConstantInt *CI;
466     if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
467       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
468       Result.mul(CI->getSExtValue());
469       return Result;
470     }
471 
472     return V;
473   }
474 
475   if (auto *CI = dyn_cast<ConstantInt>(V)) {
476     if (CI->uge(MaxConstraintValue))
477       return V;
478     return int64_t(CI->getZExtValue());
479   }
480 
481   if (auto *GEP = dyn_cast<GEPOperator>(V))
482     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
483 
484   Value *Op0;
485   bool IsKnownNonNegative = false;
486   if (match(V, m_ZExt(m_Value(Op0)))) {
487     IsKnownNonNegative = true;
488     V = Op0;
489   }
490 
491   Value *Op1;
492   ConstantInt *CI;
493   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
494     return MergeResults(Op0, Op1, IsSigned);
495   }
496   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
497     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
498       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
499                                  ConstantInt::get(Op0->getType(), 0));
500     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
501       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
502                                  ConstantInt::get(Op1->getType(), 0));
503 
504     return MergeResults(Op0, Op1, IsSigned);
505   }
506 
507   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
508       canUseSExt(CI)) {
509     Preconditions.emplace_back(
510         CmpInst::ICMP_UGE, Op0,
511         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
512     return MergeResults(Op0, CI, true);
513   }
514 
515   // Decompose or as an add if there are no common bits between the operands.
516   if (match(V, m_Or(m_Value(Op0), m_ConstantInt(CI))) &&
517       haveNoCommonBitsSet(Op0, CI, DL)) {
518     return MergeResults(Op0, CI, IsSigned);
519   }
520 
521   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
522     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
523       return {V, IsKnownNonNegative};
524     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
525     Result.mul(int64_t{1} << CI->getSExtValue());
526     return Result;
527   }
528 
529   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
530       (!CI->isNegative())) {
531     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
532     Result.mul(CI->getSExtValue());
533     return Result;
534   }
535 
536   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
537     return {-1 * CI->getSExtValue(), {{1, Op0}}};
538   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
539     return {0, {{1, Op0}, {-1, Op1}}};
540 
541   return {V, IsKnownNonNegative};
542 }
543 
544 ConstraintTy
545 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
546                               SmallVectorImpl<Value *> &NewVariables) const {
547   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
548   bool IsEq = false;
549   bool IsNe = false;
550 
551   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
552   switch (Pred) {
553   case CmpInst::ICMP_UGT:
554   case CmpInst::ICMP_UGE:
555   case CmpInst::ICMP_SGT:
556   case CmpInst::ICMP_SGE: {
557     Pred = CmpInst::getSwappedPredicate(Pred);
558     std::swap(Op0, Op1);
559     break;
560   }
561   case CmpInst::ICMP_EQ:
562     if (match(Op1, m_Zero())) {
563       Pred = CmpInst::ICMP_ULE;
564     } else {
565       IsEq = true;
566       Pred = CmpInst::ICMP_ULE;
567     }
568     break;
569   case CmpInst::ICMP_NE:
570     if (match(Op1, m_Zero())) {
571       Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
572       std::swap(Op0, Op1);
573     } else {
574       IsNe = true;
575       Pred = CmpInst::ICMP_ULE;
576     }
577     break;
578   default:
579     break;
580   }
581 
582   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
583       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
584     return {};
585 
586   SmallVector<ConditionTy, 4> Preconditions;
587   bool IsSigned = CmpInst::isSigned(Pred);
588   auto &Value2Index = getValue2Index(IsSigned);
589   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
590                         Preconditions, IsSigned, DL);
591   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
592                         Preconditions, IsSigned, DL);
593   int64_t Offset1 = ADec.Offset;
594   int64_t Offset2 = BDec.Offset;
595   Offset1 *= -1;
596 
597   auto &VariablesA = ADec.Vars;
598   auto &VariablesB = BDec.Vars;
599 
600   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
601   // new entry to NewVariables.
602   DenseMap<Value *, unsigned> NewIndexMap;
603   auto GetOrAddIndex = [&Value2Index, &NewVariables,
604                         &NewIndexMap](Value *V) -> unsigned {
605     auto V2I = Value2Index.find(V);
606     if (V2I != Value2Index.end())
607       return V2I->second;
608     auto Insert =
609         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
610     if (Insert.second)
611       NewVariables.push_back(V);
612     return Insert.first->second;
613   };
614 
615   // Make sure all variables have entries in Value2Index or NewVariables.
616   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
617     GetOrAddIndex(KV.Variable);
618 
619   // Build result constraint, by first adding all coefficients from A and then
620   // subtracting all coefficients from B.
621   ConstraintTy Res(
622       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
623       IsSigned, IsEq, IsNe);
624   // Collect variables that are known to be positive in all uses in the
625   // constraint.
626   DenseMap<Value *, bool> KnownNonNegativeVariables;
627   auto &R = Res.Coefficients;
628   for (const auto &KV : VariablesA) {
629     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
630     auto I =
631         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
632     I.first->second &= KV.IsKnownNonNegative;
633   }
634 
635   for (const auto &KV : VariablesB) {
636     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
637                     R[GetOrAddIndex(KV.Variable)]))
638       return {};
639     auto I =
640         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
641     I.first->second &= KV.IsKnownNonNegative;
642   }
643 
644   int64_t OffsetSum;
645   if (AddOverflow(Offset1, Offset2, OffsetSum))
646     return {};
647   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
648     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
649       return {};
650   R[0] = OffsetSum;
651   Res.Preconditions = std::move(Preconditions);
652 
653   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
654   // variables.
655   while (!NewVariables.empty()) {
656     int64_t Last = R.back();
657     if (Last != 0)
658       break;
659     R.pop_back();
660     Value *RemovedV = NewVariables.pop_back_val();
661     NewIndexMap.erase(RemovedV);
662   }
663 
664   // Add extra constraints for variables that are known positive.
665   for (auto &KV : KnownNonNegativeVariables) {
666     if (!KV.second ||
667         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
668       continue;
669     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
670     C[GetOrAddIndex(KV.first)] = -1;
671     Res.ExtraInfo.push_back(C);
672   }
673   return Res;
674 }
675 
676 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
677                                                      Value *Op0,
678                                                      Value *Op1) const {
679   Constant *NullC = Constant::getNullValue(Op0->getType());
680   // Handle trivially true compares directly to avoid adding V UGE 0 constraints
681   // for all variables in the unsigned system.
682   if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
683       (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
684     auto &Value2Index = getValue2Index(false);
685     // Return constraint that's trivially true.
686     return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
687                         false, false);
688   }
689 
690   // If both operands are known to be non-negative, change signed predicates to
691   // unsigned ones. This increases the reasoning effectiveness in combination
692   // with the signed <-> unsigned transfer logic.
693   if (CmpInst::isSigned(Pred) &&
694       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
695       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
696     Pred = CmpInst::getUnsignedPredicate(Pred);
697 
698   SmallVector<Value *> NewVariables;
699   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
700   if (!NewVariables.empty())
701     return {};
702   return R;
703 }
704 
705 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
706   return Coefficients.size() > 0 &&
707          all_of(Preconditions, [&Info](const ConditionTy &C) {
708            return Info.doesHold(C.Pred, C.Op0, C.Op1);
709          });
710 }
711 
712 std::optional<bool>
713 ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
714   bool IsConditionImplied = CS.isConditionImplied(Coefficients);
715 
716   if (IsEq || IsNe) {
717     auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
718     bool IsNegatedOrEqualImplied =
719         !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
720 
721     // In order to check that `%a == %b` is true (equality), both conditions `%a
722     // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
723     // is true), we return true if they both hold, false in the other cases.
724     if (IsConditionImplied && IsNegatedOrEqualImplied)
725       return IsEq;
726 
727     auto Negated = ConstraintSystem::negate(Coefficients);
728     bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
729 
730     auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
731     bool IsStrictLessThanImplied =
732         !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
733 
734     // In order to check that `%a != %b` is true (non-equality), either
735     // condition `%a > %b` or `%a < %b` must hold true. When checking for
736     // non-equality (`IsNe` is true), we return true if one of the two holds,
737     // false in the other cases.
738     if (IsNegatedImplied || IsStrictLessThanImplied)
739       return IsNe;
740 
741     return std::nullopt;
742   }
743 
744   if (IsConditionImplied)
745     return true;
746 
747   auto Negated = ConstraintSystem::negate(Coefficients);
748   auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
749   if (IsNegatedImplied)
750     return false;
751 
752   // Neither the condition nor its negated holds, did not prove anything.
753   return std::nullopt;
754 }
755 
756 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
757                               Value *B) const {
758   auto R = getConstraintForSolving(Pred, A, B);
759   return R.isValid(*this) &&
760          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
761 }
762 
763 void ConstraintInfo::transferToOtherSystem(
764     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
765     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
766   // Check if we can combine facts from the signed and unsigned systems to
767   // derive additional facts.
768   if (!A->getType()->isIntegerTy())
769     return;
770   // FIXME: This currently depends on the order we add facts. Ideally we
771   // would first add all known facts and only then try to add additional
772   // facts.
773   switch (Pred) {
774   default:
775     break;
776   case CmpInst::ICMP_ULT:
777   case CmpInst::ICMP_ULE:
778     //  If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
779     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
780       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
781               NumOut, DFSInStack);
782       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
783               DFSInStack);
784     }
785     break;
786   case CmpInst::ICMP_UGE:
787   case CmpInst::ICMP_UGT:
788     //  If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
789     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) {
790       addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
791               NumOut, DFSInStack);
792       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
793               DFSInStack);
794     }
795     break;
796   case CmpInst::ICMP_SLT:
797     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
798       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
799     break;
800   case CmpInst::ICMP_SGT: {
801     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
802       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
803               NumOut, DFSInStack);
804     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0)))
805       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
806 
807     break;
808   }
809   case CmpInst::ICMP_SGE:
810     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
811       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
812     }
813     break;
814   }
815 }
816 
817 #ifndef NDEBUG
818 
819 static void dumpConstraint(ArrayRef<int64_t> C,
820                            const DenseMap<Value *, unsigned> &Value2Index) {
821   ConstraintSystem CS(Value2Index);
822   CS.addVariableRowFill(C);
823   CS.dump();
824 }
825 #endif
826 
827 void State::addInfoForInductions(BasicBlock &BB) {
828   auto *L = LI.getLoopFor(&BB);
829   if (!L || L->getHeader() != &BB)
830     return;
831 
832   Value *A;
833   Value *B;
834   CmpInst::Predicate Pred;
835 
836   if (!match(BB.getTerminator(),
837              m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
838     return;
839   PHINode *PN = dyn_cast<PHINode>(A);
840   if (!PN) {
841     Pred = CmpInst::getSwappedPredicate(Pred);
842     std::swap(A, B);
843     PN = dyn_cast<PHINode>(A);
844   }
845 
846   if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
847       !SE.isSCEVable(PN->getType()))
848     return;
849 
850   BasicBlock *InLoopSucc = nullptr;
851   if (Pred == CmpInst::ICMP_NE)
852     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
853   else if (Pred == CmpInst::ICMP_EQ)
854     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
855   else
856     return;
857 
858   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
859     return;
860 
861   auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
862   BasicBlock *LoopPred = L->getLoopPredecessor();
863   if (!AR || !LoopPred)
864     return;
865 
866   const SCEV *StartSCEV = AR->getStart();
867   Value *StartValue = nullptr;
868   if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
869     StartValue = C->getValue();
870   } else {
871     StartValue = PN->getIncomingValueForBlock(LoopPred);
872     assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
873   }
874 
875   DomTreeNode *DTN = DT.getNode(InLoopSucc);
876   auto Inc = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
877   bool MonotonicallyIncreasing =
878       Inc && *Inc == ScalarEvolution::MonotonicallyIncreasing;
879   if (MonotonicallyIncreasing) {
880     // SCEV guarantees that AR does not wrap, so PN >= StartValue can be added
881     // unconditionally.
882     WorkList.push_back(
883         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
884   }
885 
886   APInt StepOffset;
887   if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
888     StepOffset = C->getAPInt();
889   else
890     return;
891 
892   // Handle negative steps.
893   if (StepOffset.isNegative()) {
894     // TODO: Extend to allow steps > -1.
895     if (!(-StepOffset).isOne())
896       return;
897 
898     // AR may wrap.
899     // Add StartValue >= PN conditional on B <= StartValue which guarantees that
900     // the loop exits before wrapping with a step of -1.
901     WorkList.push_back(FactOrCheck::getConditionFact(
902         DTN, CmpInst::ICMP_UGE, StartValue, PN,
903         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
904     // Add PN > B conditional on B <= StartValue which guarantees that the loop
905     // exits when reaching B with a step of -1.
906     WorkList.push_back(FactOrCheck::getConditionFact(
907         DTN, CmpInst::ICMP_UGT, PN, B,
908         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
909     return;
910   }
911 
912   // Make sure AR either steps by 1 or that the value we compare against is a
913   // GEP based on the same start value and all offsets are a multiple of the
914   // step size, to guarantee that the induction will reach the value.
915   if (StepOffset.isZero() || StepOffset.isNegative())
916     return;
917 
918   if (!StepOffset.isOne()) {
919     auto *UpperGEP = dyn_cast<GetElementPtrInst>(B);
920     if (!UpperGEP || UpperGEP->getPointerOperand() != StartValue ||
921         !UpperGEP->isInBounds())
922       return;
923 
924     MapVector<Value *, APInt> UpperVariableOffsets;
925     APInt UpperConstantOffset(StepOffset.getBitWidth(), 0);
926     const DataLayout &DL = BB.getModule()->getDataLayout();
927     if (!UpperGEP->collectOffset(DL, StepOffset.getBitWidth(),
928                                  UpperVariableOffsets, UpperConstantOffset))
929       return;
930     // All variable offsets and the constant offset have to be a multiple of the
931     // step.
932     if (!UpperConstantOffset.urem(StepOffset).isZero() ||
933         any_of(UpperVariableOffsets, [&StepOffset](const auto &P) {
934           return !P.second.urem(StepOffset).isZero();
935         }))
936       return;
937   }
938 
939   // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
940   // guarantees that the loop exits before wrapping in combination with the
941   // restrictions on B and the step above.
942   if (!MonotonicallyIncreasing) {
943     WorkList.push_back(FactOrCheck::getConditionFact(
944         DTN, CmpInst::ICMP_UGE, PN, StartValue,
945         ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
946   }
947   WorkList.push_back(FactOrCheck::getConditionFact(
948       DTN, CmpInst::ICMP_ULT, PN, B,
949       ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
950 }
951 
952 void State::addInfoFor(BasicBlock &BB) {
953   addInfoForInductions(BB);
954 
955   // True as long as long as the current instruction is guaranteed to execute.
956   bool GuaranteedToExecute = true;
957   // Queue conditions and assumes.
958   for (Instruction &I : BB) {
959     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
960       for (Use &U : Cmp->uses()) {
961         auto *UserI = getContextInstForUse(U);
962         auto *DTN = DT.getNode(UserI->getParent());
963         if (!DTN)
964           continue;
965         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
966       }
967       continue;
968     }
969 
970     if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) {
971       WorkList.push_back(
972           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
973       continue;
974     }
975 
976     if (isa<MinMaxIntrinsic>(&I)) {
977       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
978       continue;
979     }
980 
981     Value *A, *B;
982     CmpInst::Predicate Pred;
983     // For now, just handle assumes with a single compare as condition.
984     if (match(&I, m_Intrinsic<Intrinsic::assume>(
985                       m_ICmp(Pred, m_Value(A), m_Value(B))))) {
986       if (GuaranteedToExecute) {
987         // The assume is guaranteed to execute when BB is entered, hence Cond
988         // holds on entry to BB.
989         WorkList.emplace_back(FactOrCheck::getConditionFact(
990             DT.getNode(I.getParent()), Pred, A, B));
991       } else {
992         WorkList.emplace_back(
993             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
994       }
995     }
996     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
997   }
998 
999   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1000     for (auto &Case : Switch->cases()) {
1001       BasicBlock *Succ = Case.getCaseSuccessor();
1002       Value *V = Case.getCaseValue();
1003       if (!canAddSuccessor(BB, Succ))
1004         continue;
1005       WorkList.emplace_back(FactOrCheck::getConditionFact(
1006           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1007     }
1008     return;
1009   }
1010 
1011   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1012   if (!Br || !Br->isConditional())
1013     return;
1014 
1015   Value *Cond = Br->getCondition();
1016 
1017   // If the condition is a chain of ORs/AND and the successor only has the
1018   // current block as predecessor, queue conditions for the successor.
1019   Value *Op0, *Op1;
1020   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1021       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1022     bool IsOr = match(Cond, m_LogicalOr());
1023     bool IsAnd = match(Cond, m_LogicalAnd());
1024     // If there's a select that matches both AND and OR, we need to commit to
1025     // one of the options. Arbitrarily pick OR.
1026     if (IsOr && IsAnd)
1027       IsAnd = false;
1028 
1029     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1030     if (canAddSuccessor(BB, Successor)) {
1031       SmallVector<Value *> CondWorkList;
1032       SmallPtrSet<Value *, 8> SeenCond;
1033       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1034         if (SeenCond.insert(V).second)
1035           CondWorkList.push_back(V);
1036       };
1037       QueueValue(Op1);
1038       QueueValue(Op0);
1039       while (!CondWorkList.empty()) {
1040         Value *Cur = CondWorkList.pop_back_val();
1041         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1042           WorkList.emplace_back(FactOrCheck::getConditionFact(
1043               DT.getNode(Successor),
1044               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
1045                    : Cmp->getPredicate(),
1046               Cmp->getOperand(0), Cmp->getOperand(1)));
1047           continue;
1048         }
1049         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1050           QueueValue(Op1);
1051           QueueValue(Op0);
1052           continue;
1053         }
1054         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1055           QueueValue(Op1);
1056           QueueValue(Op0);
1057           continue;
1058         }
1059       }
1060     }
1061     return;
1062   }
1063 
1064   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1065   if (!CmpI)
1066     return;
1067   if (canAddSuccessor(BB, Br->getSuccessor(0)))
1068     WorkList.emplace_back(FactOrCheck::getConditionFact(
1069         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
1070         CmpI->getOperand(0), CmpI->getOperand(1)));
1071   if (canAddSuccessor(BB, Br->getSuccessor(1)))
1072     WorkList.emplace_back(FactOrCheck::getConditionFact(
1073         DT.getNode(Br->getSuccessor(1)),
1074         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
1075         CmpI->getOperand(1)));
1076 }
1077 
1078 namespace {
1079 /// Helper to keep track of a condition and if it should be treated as negated
1080 /// for reproducer construction.
1081 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1082 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1083 struct ReproducerEntry {
1084   ICmpInst::Predicate Pred;
1085   Value *LHS;
1086   Value *RHS;
1087 
1088   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1089       : Pred(Pred), LHS(LHS), RHS(RHS) {}
1090 };
1091 } // namespace
1092 
1093 /// Helper function to generate a reproducer function for simplifying \p Cond.
1094 /// The reproducer function contains a series of @llvm.assume calls, one for
1095 /// each condition in \p Stack. For each condition, the operand instruction are
1096 /// cloned until we reach operands that have an entry in \p Value2Index. Those
1097 /// will then be added as function arguments. \p DT is used to order cloned
1098 /// instructions. The reproducer function will get added to \p M, if it is
1099 /// non-null. Otherwise no reproducer function is generated.
1100 static void generateReproducer(CmpInst *Cond, Module *M,
1101                                ArrayRef<ReproducerEntry> Stack,
1102                                ConstraintInfo &Info, DominatorTree &DT) {
1103   if (!M)
1104     return;
1105 
1106   LLVMContext &Ctx = Cond->getContext();
1107 
1108   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1109 
1110   ValueToValueMapTy Old2New;
1111   SmallVector<Value *> Args;
1112   SmallPtrSet<Value *, 8> Seen;
1113   // Traverse Cond and its operands recursively until we reach a value that's in
1114   // Value2Index or not an instruction, or not a operation that
1115   // ConstraintElimination can decompose. Such values will be considered as
1116   // external inputs to the reproducer, they are collected and added as function
1117   // arguments later.
1118   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1119     auto &Value2Index = Info.getValue2Index(IsSigned);
1120     SmallVector<Value *, 4> WorkList(Ops);
1121     while (!WorkList.empty()) {
1122       Value *V = WorkList.pop_back_val();
1123       if (!Seen.insert(V).second)
1124         continue;
1125       if (Old2New.find(V) != Old2New.end())
1126         continue;
1127       if (isa<Constant>(V))
1128         continue;
1129 
1130       auto *I = dyn_cast<Instruction>(V);
1131       if (Value2Index.contains(V) || !I ||
1132           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1133         Old2New[V] = V;
1134         Args.push_back(V);
1135         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
1136       } else {
1137         append_range(WorkList, I->operands());
1138       }
1139     }
1140   };
1141 
1142   for (auto &Entry : Stack)
1143     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1144       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1145   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1146 
1147   SmallVector<Type *> ParamTys;
1148   for (auto *P : Args)
1149     ParamTys.push_back(P->getType());
1150 
1151   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1152                                         /*isVarArg=*/false);
1153   Function *F = Function::Create(FTy, Function::ExternalLinkage,
1154                                  Cond->getModule()->getName() +
1155                                      Cond->getFunction()->getName() + "repro",
1156                                  M);
1157   // Add arguments to the reproducer function for each external value collected.
1158   for (unsigned I = 0; I < Args.size(); ++I) {
1159     F->getArg(I)->setName(Args[I]->getName());
1160     Old2New[Args[I]] = F->getArg(I);
1161   }
1162 
1163   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1164   IRBuilder<> Builder(Entry);
1165   Builder.CreateRet(Builder.getTrue());
1166   Builder.SetInsertPoint(Entry->getTerminator());
1167 
1168   // Clone instructions in \p Ops and their operands recursively until reaching
1169   // an value in Value2Index (external input to the reproducer). Update Old2New
1170   // mapping for the original and cloned instructions. Sort instructions to
1171   // clone by dominance, then insert the cloned instructions in the function.
1172   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1173     SmallVector<Value *, 4> WorkList(Ops);
1174     SmallVector<Instruction *> ToClone;
1175     auto &Value2Index = Info.getValue2Index(IsSigned);
1176     while (!WorkList.empty()) {
1177       Value *V = WorkList.pop_back_val();
1178       if (Old2New.find(V) != Old2New.end())
1179         continue;
1180 
1181       auto *I = dyn_cast<Instruction>(V);
1182       if (!Value2Index.contains(V) && I) {
1183         Old2New[V] = nullptr;
1184         ToClone.push_back(I);
1185         append_range(WorkList, I->operands());
1186       }
1187     }
1188 
1189     sort(ToClone,
1190          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1191     for (Instruction *I : ToClone) {
1192       Instruction *Cloned = I->clone();
1193       Old2New[I] = Cloned;
1194       Old2New[I]->setName(I->getName());
1195       Cloned->insertBefore(&*Builder.GetInsertPoint());
1196       Cloned->dropUnknownNonDebugMetadata();
1197       Cloned->setDebugLoc({});
1198     }
1199   };
1200 
1201   // Materialize the assumptions for the reproducer using the entries in Stack.
1202   // That is, first clone the operands of the condition recursively until we
1203   // reach an external input to the reproducer and add them to the reproducer
1204   // function. Then add an ICmp for the condition (with the inverse predicate if
1205   // the entry is negated) and an assert using the ICmp.
1206   for (auto &Entry : Stack) {
1207     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1208       continue;
1209 
1210     LLVM_DEBUG(
1211         dbgs() << "  Materializing assumption icmp " << Entry.Pred << ' ';
1212         Entry.LHS->printAsOperand(dbgs(), /*PrintType=*/true); dbgs() << ", ";
1213         Entry.RHS->printAsOperand(dbgs(), /*PrintType=*/false); dbgs() << "\n");
1214     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1215 
1216     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1217     Builder.CreateAssumption(Cmp);
1218   }
1219 
1220   // Finally, clone the condition to reproduce and remap instruction operands in
1221   // the reproducer using Old2New.
1222   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1223   Entry->getTerminator()->setOperand(0, Cond);
1224   remapInstructionsInBlocks({Entry}, Old2New);
1225 
1226   assert(!verifyFunction(*F, &dbgs()));
1227 }
1228 
1229 static std::optional<bool> checkCondition(CmpInst *Cmp, ConstraintInfo &Info,
1230                                           unsigned NumIn, unsigned NumOut,
1231                                           Instruction *ContextInst) {
1232   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
1233 
1234   CmpInst::Predicate Pred = Cmp->getPredicate();
1235   Value *A = Cmp->getOperand(0);
1236   Value *B = Cmp->getOperand(1);
1237 
1238   auto R = Info.getConstraintForSolving(Pred, A, B);
1239   if (R.empty() || !R.isValid(Info)){
1240     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
1241     return std::nullopt;
1242   }
1243 
1244   auto &CSToUse = Info.getCS(R.IsSigned);
1245 
1246   // If there was extra information collected during decomposition, apply
1247   // it now and remove it immediately once we are done with reasoning
1248   // about the constraint.
1249   for (auto &Row : R.ExtraInfo)
1250     CSToUse.addVariableRow(Row);
1251   auto InfoRestorer = make_scope_exit([&]() {
1252     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1253       CSToUse.popLastConstraint();
1254   });
1255 
1256   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1257     if (!DebugCounter::shouldExecute(EliminatedCounter))
1258       return std::nullopt;
1259 
1260     LLVM_DEBUG({
1261       if (*ImpliedCondition) {
1262         dbgs() << "Condition " << *Cmp;
1263       } else {
1264         auto InversePred = Cmp->getInversePredicate();
1265         dbgs() << "Condition " << CmpInst::getPredicateName(InversePred) << " "
1266                << *A << ", " << *B;
1267       }
1268       dbgs() << " implied by dominating constraints\n";
1269       CSToUse.dump();
1270     });
1271     return ImpliedCondition;
1272   }
1273 
1274   return std::nullopt;
1275 }
1276 
1277 static bool checkAndReplaceCondition(
1278     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1279     Instruction *ContextInst, Module *ReproducerModule,
1280     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1281     SmallVectorImpl<Instruction *> &ToRemove) {
1282   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1283     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1284     Constant *ConstantC = ConstantInt::getBool(
1285         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1286     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1287                                        ContextInst](Use &U) {
1288       auto *UserI = getContextInstForUse(U);
1289       auto *DTN = DT.getNode(UserI->getParent());
1290       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1291         return false;
1292       if (UserI->getParent() == ContextInst->getParent() &&
1293           UserI->comesBefore(ContextInst))
1294         return false;
1295 
1296       // Conditions in an assume trivially simplify to true. Skip uses
1297       // in assume calls to not destroy the available information.
1298       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1299       return !II || II->getIntrinsicID() != Intrinsic::assume;
1300     });
1301     NumCondsRemoved++;
1302     if (Cmp->use_empty())
1303       ToRemove.push_back(Cmp);
1304     return true;
1305   };
1306 
1307   if (auto ImpliedCondition =
1308           checkCondition(Cmp, Info, NumIn, NumOut, ContextInst))
1309     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1310   return false;
1311 }
1312 
1313 static void
1314 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1315                      Module *ReproducerModule,
1316                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1317                      SmallVectorImpl<StackEntry> &DFSInStack) {
1318   Info.popLastConstraint(E.IsSigned);
1319   // Remove variables in the system that went out of scope.
1320   auto &Mapping = Info.getValue2Index(E.IsSigned);
1321   for (Value *V : E.ValuesToRelease)
1322     Mapping.erase(V);
1323   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1324   DFSInStack.pop_back();
1325   if (ReproducerModule)
1326     ReproducerCondStack.pop_back();
1327 }
1328 
1329 /// Check if the first condition for an AND implies the second.
1330 static bool checkAndSecondOpImpliedByFirst(
1331     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1332     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1333     SmallVectorImpl<StackEntry> &DFSInStack) {
1334 
1335   CmpInst::Predicate Pred;
1336   Value *A, *B;
1337   Instruction *And = CB.getContextInst();
1338   if (!match(And->getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1339     return false;
1340 
1341   // Optimistically add fact from first condition.
1342   unsigned OldSize = DFSInStack.size();
1343   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1344   if (OldSize == DFSInStack.size())
1345     return false;
1346 
1347   bool Changed = false;
1348   // Check if the second condition can be simplified now.
1349   if (auto ImpliedCondition =
1350           checkCondition(cast<ICmpInst>(And->getOperand(1)), Info, CB.NumIn,
1351                          CB.NumOut, CB.getContextInst())) {
1352     And->setOperand(1, ConstantInt::getBool(And->getType(), *ImpliedCondition));
1353     Changed = true;
1354   }
1355 
1356   // Remove entries again.
1357   while (OldSize < DFSInStack.size()) {
1358     StackEntry E = DFSInStack.back();
1359     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1360                          DFSInStack);
1361   }
1362   return Changed;
1363 }
1364 
1365 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1366                              unsigned NumIn, unsigned NumOut,
1367                              SmallVectorImpl<StackEntry> &DFSInStack) {
1368   // If the constraint has a pre-condition, skip the constraint if it does not
1369   // hold.
1370   SmallVector<Value *> NewVariables;
1371   auto R = getConstraint(Pred, A, B, NewVariables);
1372 
1373   // TODO: Support non-equality for facts as well.
1374   if (!R.isValid(*this) || R.isNe())
1375     return;
1376 
1377   LLVM_DEBUG(dbgs() << "Adding '" << Pred << " ";
1378              A->printAsOperand(dbgs(), false); dbgs() << ", ";
1379              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
1380   bool Added = false;
1381   auto &CSToUse = getCS(R.IsSigned);
1382   if (R.Coefficients.empty())
1383     return;
1384 
1385   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1386 
1387   // If R has been added to the system, add the new variables and queue it for
1388   // removal once it goes out-of-scope.
1389   if (Added) {
1390     SmallVector<Value *, 2> ValuesToRelease;
1391     auto &Value2Index = getValue2Index(R.IsSigned);
1392     for (Value *V : NewVariables) {
1393       Value2Index.insert({V, Value2Index.size() + 1});
1394       ValuesToRelease.push_back(V);
1395     }
1396 
1397     LLVM_DEBUG({
1398       dbgs() << "  constraint: ";
1399       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1400       dbgs() << "\n";
1401     });
1402 
1403     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1404                             std::move(ValuesToRelease));
1405 
1406     if (R.isEq()) {
1407       // Also add the inverted constraint for equality constraints.
1408       for (auto &Coeff : R.Coefficients)
1409         Coeff *= -1;
1410       CSToUse.addVariableRowFill(R.Coefficients);
1411 
1412       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1413                               SmallVector<Value *, 2>());
1414     }
1415   }
1416 }
1417 
1418 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1419                                    SmallVectorImpl<Instruction *> &ToRemove) {
1420   bool Changed = false;
1421   IRBuilder<> Builder(II->getParent(), II->getIterator());
1422   Value *Sub = nullptr;
1423   for (User *U : make_early_inc_range(II->users())) {
1424     if (match(U, m_ExtractValue<0>(m_Value()))) {
1425       if (!Sub)
1426         Sub = Builder.CreateSub(A, B);
1427       U->replaceAllUsesWith(Sub);
1428       Changed = true;
1429     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1430       U->replaceAllUsesWith(Builder.getFalse());
1431       Changed = true;
1432     } else
1433       continue;
1434 
1435     if (U->use_empty()) {
1436       auto *I = cast<Instruction>(U);
1437       ToRemove.push_back(I);
1438       I->setOperand(0, PoisonValue::get(II->getType()));
1439       Changed = true;
1440     }
1441   }
1442 
1443   if (II->use_empty()) {
1444     II->eraseFromParent();
1445     Changed = true;
1446   }
1447   return Changed;
1448 }
1449 
1450 static bool
1451 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1452                           SmallVectorImpl<Instruction *> &ToRemove) {
1453   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1454                               ConstraintInfo &Info) {
1455     auto R = Info.getConstraintForSolving(Pred, A, B);
1456     if (R.size() < 2 || !R.isValid(Info))
1457       return false;
1458 
1459     auto &CSToUse = Info.getCS(R.IsSigned);
1460     return CSToUse.isConditionImplied(R.Coefficients);
1461   };
1462 
1463   bool Changed = false;
1464   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1465     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1466     // can be simplified to a regular sub.
1467     Value *A = II->getArgOperand(0);
1468     Value *B = II->getArgOperand(1);
1469     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1470         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1471                            ConstantInt::get(A->getType(), 0), Info))
1472       return false;
1473     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1474   }
1475   return Changed;
1476 }
1477 
1478 static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
1479                                  ScalarEvolution &SE,
1480                                  OptimizationRemarkEmitter &ORE) {
1481   bool Changed = false;
1482   DT.updateDFSNumbers();
1483   SmallVector<Value *> FunctionArgs;
1484   for (Value &Arg : F.args())
1485     FunctionArgs.push_back(&Arg);
1486   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
1487   State S(DT, LI, SE);
1488   std::unique_ptr<Module> ReproducerModule(
1489       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1490 
1491   // First, collect conditions implied by branches and blocks with their
1492   // Dominator DFS in and out numbers.
1493   for (BasicBlock &BB : F) {
1494     if (!DT.getNode(&BB))
1495       continue;
1496     S.addInfoFor(BB);
1497   }
1498 
1499   // Next, sort worklist by dominance, so that dominating conditions to check
1500   // and facts come before conditions and facts dominated by them. If a
1501   // condition to check and a fact have the same numbers, conditional facts come
1502   // first. Assume facts and checks are ordered according to their relative
1503   // order in the containing basic block. Also make sure conditions with
1504   // constant operands come before conditions without constant operands. This
1505   // increases the effectiveness of the current signed <-> unsigned fact
1506   // transfer logic.
1507   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1508     auto HasNoConstOp = [](const FactOrCheck &B) {
1509       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1510       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1511       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1512     };
1513     // If both entries have the same In numbers, conditional facts come first.
1514     // Otherwise use the relative order in the basic block.
1515     if (A.NumIn == B.NumIn) {
1516       if (A.isConditionFact() && B.isConditionFact()) {
1517         bool NoConstOpA = HasNoConstOp(A);
1518         bool NoConstOpB = HasNoConstOp(B);
1519         return NoConstOpA < NoConstOpB;
1520       }
1521       if (A.isConditionFact())
1522         return true;
1523       if (B.isConditionFact())
1524         return false;
1525       auto *InstA = A.getContextInst();
1526       auto *InstB = B.getContextInst();
1527       return InstA->comesBefore(InstB);
1528     }
1529     return A.NumIn < B.NumIn;
1530   });
1531 
1532   SmallVector<Instruction *> ToRemove;
1533 
1534   // Finally, process ordered worklist and eliminate implied conditions.
1535   SmallVector<StackEntry, 16> DFSInStack;
1536   SmallVector<ReproducerEntry> ReproducerCondStack;
1537   for (FactOrCheck &CB : S.WorkList) {
1538     // First, pop entries from the stack that are out-of-scope for CB. Remove
1539     // the corresponding entry from the constraint system.
1540     while (!DFSInStack.empty()) {
1541       auto &E = DFSInStack.back();
1542       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1543                         << "\n");
1544       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1545       assert(E.NumIn <= CB.NumIn);
1546       if (CB.NumOut <= E.NumOut)
1547         break;
1548       LLVM_DEBUG({
1549         dbgs() << "Removing ";
1550         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1551                        Info.getValue2Index(E.IsSigned));
1552         dbgs() << "\n";
1553       });
1554       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1555                            DFSInStack);
1556     }
1557 
1558     LLVM_DEBUG(dbgs() << "Processing ");
1559 
1560     // For a block, check if any CmpInsts become known based on the current set
1561     // of constraints.
1562     if (CB.isCheck()) {
1563       Instruction *Inst = CB.getInstructionToSimplify();
1564       if (!Inst)
1565         continue;
1566       LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n");
1567       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1568         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1569       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1570         bool Simplified = checkAndReplaceCondition(
1571             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1572             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1573         if (!Simplified && match(CB.getContextInst(),
1574                                  m_LogicalAnd(m_Value(), m_Specific(Inst)))) {
1575           Simplified =
1576               checkAndSecondOpImpliedByFirst(CB, Info, ReproducerModule.get(),
1577                                              ReproducerCondStack, DFSInStack);
1578         }
1579         Changed |= Simplified;
1580       }
1581       continue;
1582     }
1583 
1584     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
1585       LLVM_DEBUG(dbgs() << "fact to add to the system: "
1586                         << CmpInst::getPredicateName(Pred) << " ";
1587                  A->printAsOperand(dbgs()); dbgs() << ", ";
1588                  B->printAsOperand(dbgs()); dbgs() << "\n");
1589       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1590         LLVM_DEBUG(
1591             dbgs()
1592             << "Skip adding constraint because system has too many rows.\n");
1593         return;
1594       }
1595 
1596       LLVM_DEBUG({
1597         dbgs() << "Processing fact to add to the system: " << Pred << " ";
1598         A->printAsOperand(dbgs());
1599         dbgs() << ", ";
1600         B->printAsOperand(dbgs(), false);
1601         dbgs() << "\n";
1602       });
1603 
1604       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1605       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1606         ReproducerCondStack.emplace_back(Pred, A, B);
1607 
1608       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1609       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1610         // Add dummy entries to ReproducerCondStack to keep it in sync with
1611         // DFSInStack.
1612         for (unsigned I = 0,
1613                       E = (DFSInStack.size() - ReproducerCondStack.size());
1614              I < E; ++I) {
1615           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1616                                            nullptr, nullptr);
1617         }
1618       }
1619     };
1620 
1621     ICmpInst::Predicate Pred;
1622     if (!CB.isConditionFact()) {
1623       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1624         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1625         AddFact(Pred, MinMax, MinMax->getLHS());
1626         AddFact(Pred, MinMax, MinMax->getRHS());
1627         continue;
1628       }
1629     }
1630 
1631     Value *A = nullptr, *B = nullptr;
1632     if (CB.isConditionFact()) {
1633       Pred = CB.Cond.Pred;
1634       A = CB.Cond.Op0;
1635       B = CB.Cond.Op1;
1636       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1637           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1))
1638         continue;
1639     } else {
1640       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1641                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
1642       (void)Matched;
1643       assert(Matched && "Must have an assume intrinsic with a icmp operand");
1644     }
1645     AddFact(Pred, A, B);
1646   }
1647 
1648   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1649     std::string S;
1650     raw_string_ostream StringS(S);
1651     ReproducerModule->print(StringS, nullptr);
1652     StringS.flush();
1653     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1654     Rem << ore::NV("module") << S;
1655     ORE.emit(Rem);
1656   }
1657 
1658 #ifndef NDEBUG
1659   unsigned SignedEntries =
1660       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1661   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1662          "updates to CS and DFSInStack are out of sync");
1663   assert(Info.getCS(true).size() == SignedEntries &&
1664          "updates to CS and DFSInStack are out of sync");
1665 #endif
1666 
1667   for (Instruction *I : ToRemove)
1668     I->eraseFromParent();
1669   return Changed;
1670 }
1671 
1672 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1673                                                  FunctionAnalysisManager &AM) {
1674   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1675   auto &LI = AM.getResult<LoopAnalysis>(F);
1676   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1677   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1678   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1679     return PreservedAnalyses::all();
1680 
1681   PreservedAnalyses PA;
1682   PA.preserve<DominatorTreeAnalysis>();
1683   PA.preserve<LoopAnalysis>();
1684   PA.preserve<ScalarEvolutionAnalysis>();
1685   PA.preserveSet<CFGAnalyses>();
1686   return PA;
1687 }
1688