xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision d045e23c2d00a445e40a8c97471df023d8364f59)
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 // Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
370 struct OffsetResult {
371   Value *BasePtr;
372   APInt ConstantOffset;
373   MapVector<Value *, APInt> VariableOffsets;
374   bool AllInbounds;
375 
376   OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
377 
378   OffsetResult(GEPOperator &GEP, const DataLayout &DL)
379       : BasePtr(GEP.getPointerOperand()), AllInbounds(GEP.isInBounds()) {
380     ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
381   }
382 };
383 } // namespace
384 
385 // Try to collect variable and constant offsets for \p GEP, partly traversing
386 // nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
387 // the offset fails.
388 static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) {
389   OffsetResult Result(GEP, DL);
390   unsigned BitWidth = Result.ConstantOffset.getBitWidth();
391   if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
392                          Result.ConstantOffset))
393     return {};
394 
395   // If we have a nested GEP, check if we can combine the constant offset of the
396   // inner GEP with the outer GEP.
397   if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
398     MapVector<Value *, APInt> VariableOffsets2;
399     APInt ConstantOffset2(BitWidth, 0);
400     bool CanCollectInner = InnerGEP->collectOffset(
401         DL, BitWidth, VariableOffsets2, ConstantOffset2);
402     // TODO: Support cases with more than 1 variable offset.
403     if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
404         VariableOffsets2.size() > 1 ||
405         (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
406       // More than 1 variable index, use outer result.
407       return Result;
408     }
409     Result.BasePtr = InnerGEP->getPointerOperand();
410     Result.ConstantOffset += ConstantOffset2;
411     if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
412       Result.VariableOffsets = VariableOffsets2;
413     Result.AllInbounds &= InnerGEP->isInBounds();
414   }
415   return Result;
416 }
417 
418 static Decomposition decompose(Value *V,
419                                SmallVectorImpl<ConditionTy> &Preconditions,
420                                bool IsSigned, const DataLayout &DL);
421 
422 static bool canUseSExt(ConstantInt *CI) {
423   const APInt &Val = CI->getValue();
424   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
425 }
426 
427 static Decomposition decomposeGEP(GEPOperator &GEP,
428                                   SmallVectorImpl<ConditionTy> &Preconditions,
429                                   bool IsSigned, const DataLayout &DL) {
430   // Do not reason about pointers where the index size is larger than 64 bits,
431   // as the coefficients used to encode constraints are 64 bit integers.
432   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
433     return &GEP;
434 
435   assert(!IsSigned && "The logic below only supports decomposition for "
436                       "unsinged predicates at the moment.");
437   const auto &[BasePtr, ConstantOffset, VariableOffsets, AllInbounds] =
438       collectOffsets(GEP, DL);
439   if (!BasePtr || !AllInbounds)
440     return &GEP;
441 
442   Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
443   for (auto [Index, Scale] : VariableOffsets) {
444     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
445     IdxResult.mul(Scale.getSExtValue());
446     Result.add(IdxResult);
447 
448     // If Op0 is signed non-negative, the GEP is increasing monotonically and
449     // can be de-composed.
450     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
451       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
452                                  ConstantInt::get(Index->getType(), 0));
453   }
454   return Result;
455 }
456 
457 // Decomposes \p V into a constant offset + list of pairs { Coefficient,
458 // Variable } where Coefficient * Variable. The sum of the constant offset and
459 // pairs equals \p V.
460 static Decomposition decompose(Value *V,
461                                SmallVectorImpl<ConditionTy> &Preconditions,
462                                bool IsSigned, const DataLayout &DL) {
463 
464   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
465                                                       bool IsSignedB) {
466     auto ResA = decompose(A, Preconditions, IsSigned, DL);
467     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
468     ResA.add(ResB);
469     return ResA;
470   };
471 
472   Type *Ty = V->getType()->getScalarType();
473   if (Ty->isPointerTy() && !IsSigned) {
474     if (auto *GEP = dyn_cast<GEPOperator>(V))
475       return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
476     if (isa<ConstantPointerNull>(V))
477       return int64_t(0);
478 
479     return V;
480   }
481 
482   // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
483   // coefficient add/mul may wrap, while the operation in the full bit width
484   // would not.
485   if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
486     return V;
487 
488   // Decompose \p V used with a signed predicate.
489   if (IsSigned) {
490     if (auto *CI = dyn_cast<ConstantInt>(V)) {
491       if (canUseSExt(CI))
492         return CI->getSExtValue();
493     }
494     Value *Op0;
495     Value *Op1;
496     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
497       return MergeResults(Op0, Op1, IsSigned);
498 
499     ConstantInt *CI;
500     if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
501       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
502       Result.mul(CI->getSExtValue());
503       return Result;
504     }
505 
506     return V;
507   }
508 
509   if (auto *CI = dyn_cast<ConstantInt>(V)) {
510     if (CI->uge(MaxConstraintValue))
511       return V;
512     return int64_t(CI->getZExtValue());
513   }
514 
515   Value *Op0;
516   bool IsKnownNonNegative = false;
517   if (match(V, m_ZExt(m_Value(Op0)))) {
518     IsKnownNonNegative = true;
519     V = Op0;
520   }
521 
522   Value *Op1;
523   ConstantInt *CI;
524   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
525     return MergeResults(Op0, Op1, IsSigned);
526   }
527   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
528     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
529       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
530                                  ConstantInt::get(Op0->getType(), 0));
531     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
532       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
533                                  ConstantInt::get(Op1->getType(), 0));
534 
535     return MergeResults(Op0, Op1, IsSigned);
536   }
537 
538   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
539       canUseSExt(CI)) {
540     Preconditions.emplace_back(
541         CmpInst::ICMP_UGE, Op0,
542         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
543     return MergeResults(Op0, CI, true);
544   }
545 
546   // Decompose or as an add if there are no common bits between the operands.
547   if (match(V, m_Or(m_Value(Op0), m_ConstantInt(CI))) &&
548       haveNoCommonBitsSet(Op0, CI, DL)) {
549     return MergeResults(Op0, CI, IsSigned);
550   }
551 
552   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
553     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
554       return {V, IsKnownNonNegative};
555     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
556     Result.mul(int64_t{1} << CI->getSExtValue());
557     return Result;
558   }
559 
560   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
561       (!CI->isNegative())) {
562     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
563     Result.mul(CI->getSExtValue());
564     return Result;
565   }
566 
567   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
568     return {-1 * CI->getSExtValue(), {{1, Op0}}};
569   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
570     return {0, {{1, Op0}, {-1, Op1}}};
571 
572   return {V, IsKnownNonNegative};
573 }
574 
575 ConstraintTy
576 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
577                               SmallVectorImpl<Value *> &NewVariables) const {
578   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
579   bool IsEq = false;
580   bool IsNe = false;
581 
582   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
583   switch (Pred) {
584   case CmpInst::ICMP_UGT:
585   case CmpInst::ICMP_UGE:
586   case CmpInst::ICMP_SGT:
587   case CmpInst::ICMP_SGE: {
588     Pred = CmpInst::getSwappedPredicate(Pred);
589     std::swap(Op0, Op1);
590     break;
591   }
592   case CmpInst::ICMP_EQ:
593     if (match(Op1, m_Zero())) {
594       Pred = CmpInst::ICMP_ULE;
595     } else {
596       IsEq = true;
597       Pred = CmpInst::ICMP_ULE;
598     }
599     break;
600   case CmpInst::ICMP_NE:
601     if (match(Op1, m_Zero())) {
602       Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
603       std::swap(Op0, Op1);
604     } else {
605       IsNe = true;
606       Pred = CmpInst::ICMP_ULE;
607     }
608     break;
609   default:
610     break;
611   }
612 
613   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
614       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
615     return {};
616 
617   SmallVector<ConditionTy, 4> Preconditions;
618   bool IsSigned = CmpInst::isSigned(Pred);
619   auto &Value2Index = getValue2Index(IsSigned);
620   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
621                         Preconditions, IsSigned, DL);
622   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
623                         Preconditions, IsSigned, DL);
624   int64_t Offset1 = ADec.Offset;
625   int64_t Offset2 = BDec.Offset;
626   Offset1 *= -1;
627 
628   auto &VariablesA = ADec.Vars;
629   auto &VariablesB = BDec.Vars;
630 
631   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
632   // new entry to NewVariables.
633   DenseMap<Value *, unsigned> NewIndexMap;
634   auto GetOrAddIndex = [&Value2Index, &NewVariables,
635                         &NewIndexMap](Value *V) -> unsigned {
636     auto V2I = Value2Index.find(V);
637     if (V2I != Value2Index.end())
638       return V2I->second;
639     auto Insert =
640         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
641     if (Insert.second)
642       NewVariables.push_back(V);
643     return Insert.first->second;
644   };
645 
646   // Make sure all variables have entries in Value2Index or NewVariables.
647   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
648     GetOrAddIndex(KV.Variable);
649 
650   // Build result constraint, by first adding all coefficients from A and then
651   // subtracting all coefficients from B.
652   ConstraintTy Res(
653       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
654       IsSigned, IsEq, IsNe);
655   // Collect variables that are known to be positive in all uses in the
656   // constraint.
657   DenseMap<Value *, bool> KnownNonNegativeVariables;
658   auto &R = Res.Coefficients;
659   for (const auto &KV : VariablesA) {
660     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
661     auto I =
662         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
663     I.first->second &= KV.IsKnownNonNegative;
664   }
665 
666   for (const auto &KV : VariablesB) {
667     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
668                     R[GetOrAddIndex(KV.Variable)]))
669       return {};
670     auto I =
671         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
672     I.first->second &= KV.IsKnownNonNegative;
673   }
674 
675   int64_t OffsetSum;
676   if (AddOverflow(Offset1, Offset2, OffsetSum))
677     return {};
678   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
679     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
680       return {};
681   R[0] = OffsetSum;
682   Res.Preconditions = std::move(Preconditions);
683 
684   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
685   // variables.
686   while (!NewVariables.empty()) {
687     int64_t Last = R.back();
688     if (Last != 0)
689       break;
690     R.pop_back();
691     Value *RemovedV = NewVariables.pop_back_val();
692     NewIndexMap.erase(RemovedV);
693   }
694 
695   // Add extra constraints for variables that are known positive.
696   for (auto &KV : KnownNonNegativeVariables) {
697     if (!KV.second ||
698         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
699       continue;
700     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
701     C[GetOrAddIndex(KV.first)] = -1;
702     Res.ExtraInfo.push_back(C);
703   }
704   return Res;
705 }
706 
707 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
708                                                      Value *Op0,
709                                                      Value *Op1) const {
710   Constant *NullC = Constant::getNullValue(Op0->getType());
711   // Handle trivially true compares directly to avoid adding V UGE 0 constraints
712   // for all variables in the unsigned system.
713   if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
714       (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
715     auto &Value2Index = getValue2Index(false);
716     // Return constraint that's trivially true.
717     return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
718                         false, false);
719   }
720 
721   // If both operands are known to be non-negative, change signed predicates to
722   // unsigned ones. This increases the reasoning effectiveness in combination
723   // with the signed <-> unsigned transfer logic.
724   if (CmpInst::isSigned(Pred) &&
725       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
726       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
727     Pred = CmpInst::getUnsignedPredicate(Pred);
728 
729   SmallVector<Value *> NewVariables;
730   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
731   if (!NewVariables.empty())
732     return {};
733   return R;
734 }
735 
736 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
737   return Coefficients.size() > 0 &&
738          all_of(Preconditions, [&Info](const ConditionTy &C) {
739            return Info.doesHold(C.Pred, C.Op0, C.Op1);
740          });
741 }
742 
743 std::optional<bool>
744 ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
745   bool IsConditionImplied = CS.isConditionImplied(Coefficients);
746 
747   if (IsEq || IsNe) {
748     auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
749     bool IsNegatedOrEqualImplied =
750         !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
751 
752     // In order to check that `%a == %b` is true (equality), both conditions `%a
753     // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
754     // is true), we return true if they both hold, false in the other cases.
755     if (IsConditionImplied && IsNegatedOrEqualImplied)
756       return IsEq;
757 
758     auto Negated = ConstraintSystem::negate(Coefficients);
759     bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
760 
761     auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
762     bool IsStrictLessThanImplied =
763         !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
764 
765     // In order to check that `%a != %b` is true (non-equality), either
766     // condition `%a > %b` or `%a < %b` must hold true. When checking for
767     // non-equality (`IsNe` is true), we return true if one of the two holds,
768     // false in the other cases.
769     if (IsNegatedImplied || IsStrictLessThanImplied)
770       return IsNe;
771 
772     return std::nullopt;
773   }
774 
775   if (IsConditionImplied)
776     return true;
777 
778   auto Negated = ConstraintSystem::negate(Coefficients);
779   auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
780   if (IsNegatedImplied)
781     return false;
782 
783   // Neither the condition nor its negated holds, did not prove anything.
784   return std::nullopt;
785 }
786 
787 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
788                               Value *B) const {
789   auto R = getConstraintForSolving(Pred, A, B);
790   return R.isValid(*this) &&
791          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
792 }
793 
794 void ConstraintInfo::transferToOtherSystem(
795     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
796     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
797   auto IsKnownNonNegative = [this](Value *V) {
798     return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
799            isKnownNonNegative(V, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1);
800   };
801   // Check if we can combine facts from the signed and unsigned systems to
802   // derive additional facts.
803   if (!A->getType()->isIntegerTy())
804     return;
805   // FIXME: This currently depends on the order we add facts. Ideally we
806   // would first add all known facts and only then try to add additional
807   // facts.
808   switch (Pred) {
809   default:
810     break;
811   case CmpInst::ICMP_ULT:
812   case CmpInst::ICMP_ULE:
813     //  If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
814     if (IsKnownNonNegative(B)) {
815       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
816               NumOut, DFSInStack);
817       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
818               DFSInStack);
819     }
820     break;
821   case CmpInst::ICMP_UGE:
822   case CmpInst::ICMP_UGT:
823     //  If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
824     if (IsKnownNonNegative(A)) {
825       addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
826               NumOut, DFSInStack);
827       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
828               DFSInStack);
829     }
830     break;
831   case CmpInst::ICMP_SLT:
832     if (IsKnownNonNegative(A))
833       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
834     break;
835   case CmpInst::ICMP_SGT: {
836     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
837       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
838               NumOut, DFSInStack);
839     if (IsKnownNonNegative(B))
840       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
841 
842     break;
843   }
844   case CmpInst::ICMP_SGE:
845     if (IsKnownNonNegative(B))
846       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
847     break;
848   }
849 }
850 
851 #ifndef NDEBUG
852 
853 static void dumpConstraint(ArrayRef<int64_t> C,
854                            const DenseMap<Value *, unsigned> &Value2Index) {
855   ConstraintSystem CS(Value2Index);
856   CS.addVariableRowFill(C);
857   CS.dump();
858 }
859 #endif
860 
861 void State::addInfoForInductions(BasicBlock &BB) {
862   auto *L = LI.getLoopFor(&BB);
863   if (!L || L->getHeader() != &BB)
864     return;
865 
866   Value *A;
867   Value *B;
868   CmpInst::Predicate Pred;
869 
870   if (!match(BB.getTerminator(),
871              m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
872     return;
873   PHINode *PN = dyn_cast<PHINode>(A);
874   if (!PN) {
875     Pred = CmpInst::getSwappedPredicate(Pred);
876     std::swap(A, B);
877     PN = dyn_cast<PHINode>(A);
878   }
879 
880   if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
881       !SE.isSCEVable(PN->getType()))
882     return;
883 
884   BasicBlock *InLoopSucc = nullptr;
885   if (Pred == CmpInst::ICMP_NE)
886     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
887   else if (Pred == CmpInst::ICMP_EQ)
888     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
889   else
890     return;
891 
892   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
893     return;
894 
895   auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
896   BasicBlock *LoopPred = L->getLoopPredecessor();
897   if (!AR || AR->getLoop() != L || !LoopPred)
898     return;
899 
900   const SCEV *StartSCEV = AR->getStart();
901   Value *StartValue = nullptr;
902   if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
903     StartValue = C->getValue();
904   } else {
905     StartValue = PN->getIncomingValueForBlock(LoopPred);
906     assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
907   }
908 
909   DomTreeNode *DTN = DT.getNode(InLoopSucc);
910   auto Inc = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
911   bool MonotonicallyIncreasing =
912       Inc && *Inc == ScalarEvolution::MonotonicallyIncreasing;
913   if (MonotonicallyIncreasing) {
914     // SCEV guarantees that AR does not wrap, so PN >= StartValue can be added
915     // unconditionally.
916     WorkList.push_back(
917         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
918   }
919 
920   APInt StepOffset;
921   if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
922     StepOffset = C->getAPInt();
923   else
924     return;
925 
926   // Make sure the bound B is loop-invariant.
927   if (!L->isLoopInvariant(B))
928     return;
929 
930   // Handle negative steps.
931   if (StepOffset.isNegative()) {
932     // TODO: Extend to allow steps > -1.
933     if (!(-StepOffset).isOne())
934       return;
935 
936     // AR may wrap.
937     // Add StartValue >= PN conditional on B <= StartValue which guarantees that
938     // the loop exits before wrapping with a step of -1.
939     WorkList.push_back(FactOrCheck::getConditionFact(
940         DTN, CmpInst::ICMP_UGE, StartValue, PN,
941         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
942     // Add PN > B conditional on B <= StartValue which guarantees that the loop
943     // exits when reaching B with a step of -1.
944     WorkList.push_back(FactOrCheck::getConditionFact(
945         DTN, CmpInst::ICMP_UGT, PN, B,
946         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
947     return;
948   }
949 
950   // Make sure AR either steps by 1 or that the value we compare against is a
951   // GEP based on the same start value and all offsets are a multiple of the
952   // step size, to guarantee that the induction will reach the value.
953   if (StepOffset.isZero() || StepOffset.isNegative())
954     return;
955 
956   if (!StepOffset.isOne()) {
957     auto *UpperGEP = dyn_cast<GetElementPtrInst>(B);
958     if (!UpperGEP || UpperGEP->getPointerOperand() != StartValue ||
959         !UpperGEP->isInBounds())
960       return;
961 
962     MapVector<Value *, APInt> UpperVariableOffsets;
963     APInt UpperConstantOffset(StepOffset.getBitWidth(), 0);
964     const DataLayout &DL = BB.getModule()->getDataLayout();
965     if (!UpperGEP->collectOffset(DL, StepOffset.getBitWidth(),
966                                  UpperVariableOffsets, UpperConstantOffset))
967       return;
968     // All variable offsets and the constant offset have to be a multiple of the
969     // step.
970     if (!UpperConstantOffset.urem(StepOffset).isZero() ||
971         any_of(UpperVariableOffsets, [&StepOffset](const auto &P) {
972           return !P.second.urem(StepOffset).isZero();
973         }))
974       return;
975   }
976 
977   // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
978   // guarantees that the loop exits before wrapping in combination with the
979   // restrictions on B and the step above.
980   if (!MonotonicallyIncreasing) {
981     WorkList.push_back(FactOrCheck::getConditionFact(
982         DTN, CmpInst::ICMP_UGE, PN, StartValue,
983         ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
984   }
985   WorkList.push_back(FactOrCheck::getConditionFact(
986       DTN, CmpInst::ICMP_ULT, PN, B,
987       ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
988 }
989 
990 void State::addInfoFor(BasicBlock &BB) {
991   addInfoForInductions(BB);
992 
993   // True as long as long as the current instruction is guaranteed to execute.
994   bool GuaranteedToExecute = true;
995   // Queue conditions and assumes.
996   for (Instruction &I : BB) {
997     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
998       for (Use &U : Cmp->uses()) {
999         auto *UserI = getContextInstForUse(U);
1000         auto *DTN = DT.getNode(UserI->getParent());
1001         if (!DTN)
1002           continue;
1003         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1004       }
1005       continue;
1006     }
1007 
1008     if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) {
1009       WorkList.push_back(
1010           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1011       continue;
1012     }
1013 
1014     if (isa<MinMaxIntrinsic>(&I)) {
1015       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1016       continue;
1017     }
1018 
1019     Value *A, *B;
1020     CmpInst::Predicate Pred;
1021     // For now, just handle assumes with a single compare as condition.
1022     if (match(&I, m_Intrinsic<Intrinsic::assume>(
1023                       m_ICmp(Pred, m_Value(A), m_Value(B))))) {
1024       if (GuaranteedToExecute) {
1025         // The assume is guaranteed to execute when BB is entered, hence Cond
1026         // holds on entry to BB.
1027         WorkList.emplace_back(FactOrCheck::getConditionFact(
1028             DT.getNode(I.getParent()), Pred, A, B));
1029       } else {
1030         WorkList.emplace_back(
1031             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1032       }
1033     }
1034     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1035   }
1036 
1037   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1038     for (auto &Case : Switch->cases()) {
1039       BasicBlock *Succ = Case.getCaseSuccessor();
1040       Value *V = Case.getCaseValue();
1041       if (!canAddSuccessor(BB, Succ))
1042         continue;
1043       WorkList.emplace_back(FactOrCheck::getConditionFact(
1044           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1045     }
1046     return;
1047   }
1048 
1049   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1050   if (!Br || !Br->isConditional())
1051     return;
1052 
1053   Value *Cond = Br->getCondition();
1054 
1055   // If the condition is a chain of ORs/AND and the successor only has the
1056   // current block as predecessor, queue conditions for the successor.
1057   Value *Op0, *Op1;
1058   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1059       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1060     bool IsOr = match(Cond, m_LogicalOr());
1061     bool IsAnd = match(Cond, m_LogicalAnd());
1062     // If there's a select that matches both AND and OR, we need to commit to
1063     // one of the options. Arbitrarily pick OR.
1064     if (IsOr && IsAnd)
1065       IsAnd = false;
1066 
1067     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1068     if (canAddSuccessor(BB, Successor)) {
1069       SmallVector<Value *> CondWorkList;
1070       SmallPtrSet<Value *, 8> SeenCond;
1071       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1072         if (SeenCond.insert(V).second)
1073           CondWorkList.push_back(V);
1074       };
1075       QueueValue(Op1);
1076       QueueValue(Op0);
1077       while (!CondWorkList.empty()) {
1078         Value *Cur = CondWorkList.pop_back_val();
1079         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1080           WorkList.emplace_back(FactOrCheck::getConditionFact(
1081               DT.getNode(Successor),
1082               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
1083                    : Cmp->getPredicate(),
1084               Cmp->getOperand(0), Cmp->getOperand(1)));
1085           continue;
1086         }
1087         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1088           QueueValue(Op1);
1089           QueueValue(Op0);
1090           continue;
1091         }
1092         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1093           QueueValue(Op1);
1094           QueueValue(Op0);
1095           continue;
1096         }
1097       }
1098     }
1099     return;
1100   }
1101 
1102   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1103   if (!CmpI)
1104     return;
1105   if (canAddSuccessor(BB, Br->getSuccessor(0)))
1106     WorkList.emplace_back(FactOrCheck::getConditionFact(
1107         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
1108         CmpI->getOperand(0), CmpI->getOperand(1)));
1109   if (canAddSuccessor(BB, Br->getSuccessor(1)))
1110     WorkList.emplace_back(FactOrCheck::getConditionFact(
1111         DT.getNode(Br->getSuccessor(1)),
1112         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
1113         CmpI->getOperand(1)));
1114 }
1115 
1116 namespace {
1117 /// Helper to keep track of a condition and if it should be treated as negated
1118 /// for reproducer construction.
1119 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1120 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1121 struct ReproducerEntry {
1122   ICmpInst::Predicate Pred;
1123   Value *LHS;
1124   Value *RHS;
1125 
1126   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1127       : Pred(Pred), LHS(LHS), RHS(RHS) {}
1128 };
1129 } // namespace
1130 
1131 /// Helper function to generate a reproducer function for simplifying \p Cond.
1132 /// The reproducer function contains a series of @llvm.assume calls, one for
1133 /// each condition in \p Stack. For each condition, the operand instruction are
1134 /// cloned until we reach operands that have an entry in \p Value2Index. Those
1135 /// will then be added as function arguments. \p DT is used to order cloned
1136 /// instructions. The reproducer function will get added to \p M, if it is
1137 /// non-null. Otherwise no reproducer function is generated.
1138 static void generateReproducer(CmpInst *Cond, Module *M,
1139                                ArrayRef<ReproducerEntry> Stack,
1140                                ConstraintInfo &Info, DominatorTree &DT) {
1141   if (!M)
1142     return;
1143 
1144   LLVMContext &Ctx = Cond->getContext();
1145 
1146   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1147 
1148   ValueToValueMapTy Old2New;
1149   SmallVector<Value *> Args;
1150   SmallPtrSet<Value *, 8> Seen;
1151   // Traverse Cond and its operands recursively until we reach a value that's in
1152   // Value2Index or not an instruction, or not a operation that
1153   // ConstraintElimination can decompose. Such values will be considered as
1154   // external inputs to the reproducer, they are collected and added as function
1155   // arguments later.
1156   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1157     auto &Value2Index = Info.getValue2Index(IsSigned);
1158     SmallVector<Value *, 4> WorkList(Ops);
1159     while (!WorkList.empty()) {
1160       Value *V = WorkList.pop_back_val();
1161       if (!Seen.insert(V).second)
1162         continue;
1163       if (Old2New.find(V) != Old2New.end())
1164         continue;
1165       if (isa<Constant>(V))
1166         continue;
1167 
1168       auto *I = dyn_cast<Instruction>(V);
1169       if (Value2Index.contains(V) || !I ||
1170           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1171         Old2New[V] = V;
1172         Args.push_back(V);
1173         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
1174       } else {
1175         append_range(WorkList, I->operands());
1176       }
1177     }
1178   };
1179 
1180   for (auto &Entry : Stack)
1181     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1182       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1183   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1184 
1185   SmallVector<Type *> ParamTys;
1186   for (auto *P : Args)
1187     ParamTys.push_back(P->getType());
1188 
1189   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1190                                         /*isVarArg=*/false);
1191   Function *F = Function::Create(FTy, Function::ExternalLinkage,
1192                                  Cond->getModule()->getName() +
1193                                      Cond->getFunction()->getName() + "repro",
1194                                  M);
1195   // Add arguments to the reproducer function for each external value collected.
1196   for (unsigned I = 0; I < Args.size(); ++I) {
1197     F->getArg(I)->setName(Args[I]->getName());
1198     Old2New[Args[I]] = F->getArg(I);
1199   }
1200 
1201   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1202   IRBuilder<> Builder(Entry);
1203   Builder.CreateRet(Builder.getTrue());
1204   Builder.SetInsertPoint(Entry->getTerminator());
1205 
1206   // Clone instructions in \p Ops and their operands recursively until reaching
1207   // an value in Value2Index (external input to the reproducer). Update Old2New
1208   // mapping for the original and cloned instructions. Sort instructions to
1209   // clone by dominance, then insert the cloned instructions in the function.
1210   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1211     SmallVector<Value *, 4> WorkList(Ops);
1212     SmallVector<Instruction *> ToClone;
1213     auto &Value2Index = Info.getValue2Index(IsSigned);
1214     while (!WorkList.empty()) {
1215       Value *V = WorkList.pop_back_val();
1216       if (Old2New.find(V) != Old2New.end())
1217         continue;
1218 
1219       auto *I = dyn_cast<Instruction>(V);
1220       if (!Value2Index.contains(V) && I) {
1221         Old2New[V] = nullptr;
1222         ToClone.push_back(I);
1223         append_range(WorkList, I->operands());
1224       }
1225     }
1226 
1227     sort(ToClone,
1228          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1229     for (Instruction *I : ToClone) {
1230       Instruction *Cloned = I->clone();
1231       Old2New[I] = Cloned;
1232       Old2New[I]->setName(I->getName());
1233       Cloned->insertBefore(&*Builder.GetInsertPoint());
1234       Cloned->dropUnknownNonDebugMetadata();
1235       Cloned->setDebugLoc({});
1236     }
1237   };
1238 
1239   // Materialize the assumptions for the reproducer using the entries in Stack.
1240   // That is, first clone the operands of the condition recursively until we
1241   // reach an external input to the reproducer and add them to the reproducer
1242   // function. Then add an ICmp for the condition (with the inverse predicate if
1243   // the entry is negated) and an assert using the ICmp.
1244   for (auto &Entry : Stack) {
1245     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1246       continue;
1247 
1248     LLVM_DEBUG(
1249         dbgs() << "  Materializing assumption icmp " << Entry.Pred << ' ';
1250         Entry.LHS->printAsOperand(dbgs(), /*PrintType=*/true); dbgs() << ", ";
1251         Entry.RHS->printAsOperand(dbgs(), /*PrintType=*/false); dbgs() << "\n");
1252     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1253 
1254     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1255     Builder.CreateAssumption(Cmp);
1256   }
1257 
1258   // Finally, clone the condition to reproduce and remap instruction operands in
1259   // the reproducer using Old2New.
1260   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1261   Entry->getTerminator()->setOperand(0, Cond);
1262   remapInstructionsInBlocks({Entry}, Old2New);
1263 
1264   assert(!verifyFunction(*F, &dbgs()));
1265 }
1266 
1267 static std::optional<bool> checkCondition(CmpInst *Cmp, ConstraintInfo &Info,
1268                                           unsigned NumIn, unsigned NumOut,
1269                                           Instruction *ContextInst) {
1270   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
1271 
1272   CmpInst::Predicate Pred = Cmp->getPredicate();
1273   Value *A = Cmp->getOperand(0);
1274   Value *B = Cmp->getOperand(1);
1275 
1276   auto R = Info.getConstraintForSolving(Pred, A, B);
1277   if (R.empty() || !R.isValid(Info)){
1278     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
1279     return std::nullopt;
1280   }
1281 
1282   auto &CSToUse = Info.getCS(R.IsSigned);
1283 
1284   // If there was extra information collected during decomposition, apply
1285   // it now and remove it immediately once we are done with reasoning
1286   // about the constraint.
1287   for (auto &Row : R.ExtraInfo)
1288     CSToUse.addVariableRow(Row);
1289   auto InfoRestorer = make_scope_exit([&]() {
1290     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1291       CSToUse.popLastConstraint();
1292   });
1293 
1294   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1295     if (!DebugCounter::shouldExecute(EliminatedCounter))
1296       return std::nullopt;
1297 
1298     LLVM_DEBUG({
1299       if (*ImpliedCondition) {
1300         dbgs() << "Condition " << *Cmp;
1301       } else {
1302         auto InversePred = Cmp->getInversePredicate();
1303         dbgs() << "Condition " << CmpInst::getPredicateName(InversePred) << " "
1304                << *A << ", " << *B;
1305       }
1306       dbgs() << " implied by dominating constraints\n";
1307       CSToUse.dump();
1308     });
1309     return ImpliedCondition;
1310   }
1311 
1312   return std::nullopt;
1313 }
1314 
1315 static bool checkAndReplaceCondition(
1316     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1317     Instruction *ContextInst, Module *ReproducerModule,
1318     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1319     SmallVectorImpl<Instruction *> &ToRemove) {
1320   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1321     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1322     Constant *ConstantC = ConstantInt::getBool(
1323         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1324     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1325                                        ContextInst](Use &U) {
1326       auto *UserI = getContextInstForUse(U);
1327       auto *DTN = DT.getNode(UserI->getParent());
1328       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1329         return false;
1330       if (UserI->getParent() == ContextInst->getParent() &&
1331           UserI->comesBefore(ContextInst))
1332         return false;
1333 
1334       // Conditions in an assume trivially simplify to true. Skip uses
1335       // in assume calls to not destroy the available information.
1336       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1337       return !II || II->getIntrinsicID() != Intrinsic::assume;
1338     });
1339     NumCondsRemoved++;
1340     if (Cmp->use_empty())
1341       ToRemove.push_back(Cmp);
1342     return true;
1343   };
1344 
1345   if (auto ImpliedCondition =
1346           checkCondition(Cmp, Info, NumIn, NumOut, ContextInst))
1347     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1348   return false;
1349 }
1350 
1351 static void
1352 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1353                      Module *ReproducerModule,
1354                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1355                      SmallVectorImpl<StackEntry> &DFSInStack) {
1356   Info.popLastConstraint(E.IsSigned);
1357   // Remove variables in the system that went out of scope.
1358   auto &Mapping = Info.getValue2Index(E.IsSigned);
1359   for (Value *V : E.ValuesToRelease)
1360     Mapping.erase(V);
1361   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1362   DFSInStack.pop_back();
1363   if (ReproducerModule)
1364     ReproducerCondStack.pop_back();
1365 }
1366 
1367 /// Check if the first condition for an AND implies the second.
1368 static bool checkAndSecondOpImpliedByFirst(
1369     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1370     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1371     SmallVectorImpl<StackEntry> &DFSInStack) {
1372 
1373   CmpInst::Predicate Pred;
1374   Value *A, *B;
1375   Instruction *And = CB.getContextInst();
1376   if (!match(And->getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1377     return false;
1378 
1379   // Optimistically add fact from first condition.
1380   unsigned OldSize = DFSInStack.size();
1381   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1382   if (OldSize == DFSInStack.size())
1383     return false;
1384 
1385   bool Changed = false;
1386   // Check if the second condition can be simplified now.
1387   if (auto ImpliedCondition =
1388           checkCondition(cast<ICmpInst>(And->getOperand(1)), Info, CB.NumIn,
1389                          CB.NumOut, CB.getContextInst())) {
1390     And->setOperand(1, ConstantInt::getBool(And->getType(), *ImpliedCondition));
1391     Changed = true;
1392   }
1393 
1394   // Remove entries again.
1395   while (OldSize < DFSInStack.size()) {
1396     StackEntry E = DFSInStack.back();
1397     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1398                          DFSInStack);
1399   }
1400   return Changed;
1401 }
1402 
1403 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1404                              unsigned NumIn, unsigned NumOut,
1405                              SmallVectorImpl<StackEntry> &DFSInStack) {
1406   // If the constraint has a pre-condition, skip the constraint if it does not
1407   // hold.
1408   SmallVector<Value *> NewVariables;
1409   auto R = getConstraint(Pred, A, B, NewVariables);
1410 
1411   // TODO: Support non-equality for facts as well.
1412   if (!R.isValid(*this) || R.isNe())
1413     return;
1414 
1415   LLVM_DEBUG(dbgs() << "Adding '" << Pred << " ";
1416              A->printAsOperand(dbgs(), false); dbgs() << ", ";
1417              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
1418   bool Added = false;
1419   auto &CSToUse = getCS(R.IsSigned);
1420   if (R.Coefficients.empty())
1421     return;
1422 
1423   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1424 
1425   // If R has been added to the system, add the new variables and queue it for
1426   // removal once it goes out-of-scope.
1427   if (Added) {
1428     SmallVector<Value *, 2> ValuesToRelease;
1429     auto &Value2Index = getValue2Index(R.IsSigned);
1430     for (Value *V : NewVariables) {
1431       Value2Index.insert({V, Value2Index.size() + 1});
1432       ValuesToRelease.push_back(V);
1433     }
1434 
1435     LLVM_DEBUG({
1436       dbgs() << "  constraint: ";
1437       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1438       dbgs() << "\n";
1439     });
1440 
1441     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1442                             std::move(ValuesToRelease));
1443 
1444     if (R.isEq()) {
1445       // Also add the inverted constraint for equality constraints.
1446       for (auto &Coeff : R.Coefficients)
1447         Coeff *= -1;
1448       CSToUse.addVariableRowFill(R.Coefficients);
1449 
1450       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1451                               SmallVector<Value *, 2>());
1452     }
1453   }
1454 }
1455 
1456 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1457                                    SmallVectorImpl<Instruction *> &ToRemove) {
1458   bool Changed = false;
1459   IRBuilder<> Builder(II->getParent(), II->getIterator());
1460   Value *Sub = nullptr;
1461   for (User *U : make_early_inc_range(II->users())) {
1462     if (match(U, m_ExtractValue<0>(m_Value()))) {
1463       if (!Sub)
1464         Sub = Builder.CreateSub(A, B);
1465       U->replaceAllUsesWith(Sub);
1466       Changed = true;
1467     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1468       U->replaceAllUsesWith(Builder.getFalse());
1469       Changed = true;
1470     } else
1471       continue;
1472 
1473     if (U->use_empty()) {
1474       auto *I = cast<Instruction>(U);
1475       ToRemove.push_back(I);
1476       I->setOperand(0, PoisonValue::get(II->getType()));
1477       Changed = true;
1478     }
1479   }
1480 
1481   if (II->use_empty()) {
1482     II->eraseFromParent();
1483     Changed = true;
1484   }
1485   return Changed;
1486 }
1487 
1488 static bool
1489 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1490                           SmallVectorImpl<Instruction *> &ToRemove) {
1491   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1492                               ConstraintInfo &Info) {
1493     auto R = Info.getConstraintForSolving(Pred, A, B);
1494     if (R.size() < 2 || !R.isValid(Info))
1495       return false;
1496 
1497     auto &CSToUse = Info.getCS(R.IsSigned);
1498     return CSToUse.isConditionImplied(R.Coefficients);
1499   };
1500 
1501   bool Changed = false;
1502   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1503     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1504     // can be simplified to a regular sub.
1505     Value *A = II->getArgOperand(0);
1506     Value *B = II->getArgOperand(1);
1507     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1508         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1509                            ConstantInt::get(A->getType(), 0), Info))
1510       return false;
1511     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1512   }
1513   return Changed;
1514 }
1515 
1516 static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
1517                                  ScalarEvolution &SE,
1518                                  OptimizationRemarkEmitter &ORE) {
1519   bool Changed = false;
1520   DT.updateDFSNumbers();
1521   SmallVector<Value *> FunctionArgs;
1522   for (Value &Arg : F.args())
1523     FunctionArgs.push_back(&Arg);
1524   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
1525   State S(DT, LI, SE);
1526   std::unique_ptr<Module> ReproducerModule(
1527       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1528 
1529   // First, collect conditions implied by branches and blocks with their
1530   // Dominator DFS in and out numbers.
1531   for (BasicBlock &BB : F) {
1532     if (!DT.getNode(&BB))
1533       continue;
1534     S.addInfoFor(BB);
1535   }
1536 
1537   // Next, sort worklist by dominance, so that dominating conditions to check
1538   // and facts come before conditions and facts dominated by them. If a
1539   // condition to check and a fact have the same numbers, conditional facts come
1540   // first. Assume facts and checks are ordered according to their relative
1541   // order in the containing basic block. Also make sure conditions with
1542   // constant operands come before conditions without constant operands. This
1543   // increases the effectiveness of the current signed <-> unsigned fact
1544   // transfer logic.
1545   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1546     auto HasNoConstOp = [](const FactOrCheck &B) {
1547       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1548       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1549       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1550     };
1551     // If both entries have the same In numbers, conditional facts come first.
1552     // Otherwise use the relative order in the basic block.
1553     if (A.NumIn == B.NumIn) {
1554       if (A.isConditionFact() && B.isConditionFact()) {
1555         bool NoConstOpA = HasNoConstOp(A);
1556         bool NoConstOpB = HasNoConstOp(B);
1557         return NoConstOpA < NoConstOpB;
1558       }
1559       if (A.isConditionFact())
1560         return true;
1561       if (B.isConditionFact())
1562         return false;
1563       auto *InstA = A.getContextInst();
1564       auto *InstB = B.getContextInst();
1565       return InstA->comesBefore(InstB);
1566     }
1567     return A.NumIn < B.NumIn;
1568   });
1569 
1570   SmallVector<Instruction *> ToRemove;
1571 
1572   // Finally, process ordered worklist and eliminate implied conditions.
1573   SmallVector<StackEntry, 16> DFSInStack;
1574   SmallVector<ReproducerEntry> ReproducerCondStack;
1575   for (FactOrCheck &CB : S.WorkList) {
1576     // First, pop entries from the stack that are out-of-scope for CB. Remove
1577     // the corresponding entry from the constraint system.
1578     while (!DFSInStack.empty()) {
1579       auto &E = DFSInStack.back();
1580       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1581                         << "\n");
1582       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1583       assert(E.NumIn <= CB.NumIn);
1584       if (CB.NumOut <= E.NumOut)
1585         break;
1586       LLVM_DEBUG({
1587         dbgs() << "Removing ";
1588         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1589                        Info.getValue2Index(E.IsSigned));
1590         dbgs() << "\n";
1591       });
1592       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1593                            DFSInStack);
1594     }
1595 
1596     LLVM_DEBUG(dbgs() << "Processing ");
1597 
1598     // For a block, check if any CmpInsts become known based on the current set
1599     // of constraints.
1600     if (CB.isCheck()) {
1601       Instruction *Inst = CB.getInstructionToSimplify();
1602       if (!Inst)
1603         continue;
1604       LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n");
1605       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1606         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1607       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1608         bool Simplified = checkAndReplaceCondition(
1609             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1610             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1611         if (!Simplified && match(CB.getContextInst(),
1612                                  m_LogicalAnd(m_Value(), m_Specific(Inst)))) {
1613           Simplified =
1614               checkAndSecondOpImpliedByFirst(CB, Info, ReproducerModule.get(),
1615                                              ReproducerCondStack, DFSInStack);
1616         }
1617         Changed |= Simplified;
1618       }
1619       continue;
1620     }
1621 
1622     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
1623       LLVM_DEBUG(dbgs() << "fact to add to the system: "
1624                         << CmpInst::getPredicateName(Pred) << " ";
1625                  A->printAsOperand(dbgs()); dbgs() << ", ";
1626                  B->printAsOperand(dbgs(), false); dbgs() << "\n");
1627       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1628         LLVM_DEBUG(
1629             dbgs()
1630             << "Skip adding constraint because system has too many rows.\n");
1631         return;
1632       }
1633 
1634       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1635       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1636         ReproducerCondStack.emplace_back(Pred, A, B);
1637 
1638       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1639       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1640         // Add dummy entries to ReproducerCondStack to keep it in sync with
1641         // DFSInStack.
1642         for (unsigned I = 0,
1643                       E = (DFSInStack.size() - ReproducerCondStack.size());
1644              I < E; ++I) {
1645           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1646                                            nullptr, nullptr);
1647         }
1648       }
1649     };
1650 
1651     ICmpInst::Predicate Pred;
1652     if (!CB.isConditionFact()) {
1653       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1654         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1655         AddFact(Pred, MinMax, MinMax->getLHS());
1656         AddFact(Pred, MinMax, MinMax->getRHS());
1657         continue;
1658       }
1659     }
1660 
1661     Value *A = nullptr, *B = nullptr;
1662     if (CB.isConditionFact()) {
1663       Pred = CB.Cond.Pred;
1664       A = CB.Cond.Op0;
1665       B = CB.Cond.Op1;
1666       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1667           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1))
1668         continue;
1669     } else {
1670       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1671                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
1672       (void)Matched;
1673       assert(Matched && "Must have an assume intrinsic with a icmp operand");
1674     }
1675     AddFact(Pred, A, B);
1676   }
1677 
1678   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1679     std::string S;
1680     raw_string_ostream StringS(S);
1681     ReproducerModule->print(StringS, nullptr);
1682     StringS.flush();
1683     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1684     Rem << ore::NV("module") << S;
1685     ORE.emit(Rem);
1686   }
1687 
1688 #ifndef NDEBUG
1689   unsigned SignedEntries =
1690       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1691   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1692          "updates to CS and DFSInStack are out of sync");
1693   assert(Info.getCS(true).size() == SignedEntries &&
1694          "updates to CS and DFSInStack are out of sync");
1695 #endif
1696 
1697   for (Instruction *I : ToRemove)
1698     I->eraseFromParent();
1699   return Changed;
1700 }
1701 
1702 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1703                                                  FunctionAnalysisManager &AM) {
1704   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1705   auto &LI = AM.getResult<LoopAnalysis>(F);
1706   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1707   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1708   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1709     return PreservedAnalyses::all();
1710 
1711   PreservedAnalyses PA;
1712   PA.preserve<DominatorTreeAnalysis>();
1713   PA.preserve<LoopAnalysis>();
1714   PA.preserve<ScalarEvolutionAnalysis>();
1715   PA.preserveSet<CFGAnalyses>();
1716   return PA;
1717 }
1718