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