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