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