xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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     if (isa<MinMaxIntrinsic>(&I)) {
788       WorkList.push_back(FactOrCheck::getFact(DT.getNode(&BB), &I));
789       continue;
790     }
791 
792     Value *Cond;
793     // For now, just handle assumes with a single compare as condition.
794     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
795         isa<ICmpInst>(Cond)) {
796       if (GuaranteedToExecute) {
797         // The assume is guaranteed to execute when BB is entered, hence Cond
798         // holds on entry to BB.
799         WorkList.emplace_back(FactOrCheck::getFact(DT.getNode(I.getParent()),
800                                                    cast<Instruction>(Cond)));
801       } else {
802         WorkList.emplace_back(
803             FactOrCheck::getFact(DT.getNode(I.getParent()), &I));
804       }
805     }
806     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
807   }
808 
809   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
810   if (!Br || !Br->isConditional())
811     return;
812 
813   Value *Cond = Br->getCondition();
814 
815   // If the condition is a chain of ORs/AND and the successor only has the
816   // current block as predecessor, queue conditions for the successor.
817   Value *Op0, *Op1;
818   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
819       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
820     bool IsOr = match(Cond, m_LogicalOr());
821     bool IsAnd = match(Cond, m_LogicalAnd());
822     // If there's a select that matches both AND and OR, we need to commit to
823     // one of the options. Arbitrarily pick OR.
824     if (IsOr && IsAnd)
825       IsAnd = false;
826 
827     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
828     if (canAddSuccessor(BB, Successor)) {
829       SmallVector<Value *> CondWorkList;
830       SmallPtrSet<Value *, 8> SeenCond;
831       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
832         if (SeenCond.insert(V).second)
833           CondWorkList.push_back(V);
834       };
835       QueueValue(Op1);
836       QueueValue(Op0);
837       while (!CondWorkList.empty()) {
838         Value *Cur = CondWorkList.pop_back_val();
839         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
840           WorkList.emplace_back(
841               FactOrCheck::getFact(DT.getNode(Successor), Cmp, IsOr));
842           continue;
843         }
844         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
845           QueueValue(Op1);
846           QueueValue(Op0);
847           continue;
848         }
849         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
850           QueueValue(Op1);
851           QueueValue(Op0);
852           continue;
853         }
854       }
855     }
856     return;
857   }
858 
859   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
860   if (!CmpI)
861     return;
862   if (canAddSuccessor(BB, Br->getSuccessor(0)))
863     WorkList.emplace_back(
864         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(0)), CmpI));
865   if (canAddSuccessor(BB, Br->getSuccessor(1)))
866     WorkList.emplace_back(
867         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(1)), CmpI, true));
868 }
869 
870 namespace {
871 /// Helper to keep track of a condition and if it should be treated as negated
872 /// for reproducer construction.
873 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
874 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
875 struct ReproducerEntry {
876   ICmpInst::Predicate Pred;
877   Value *LHS;
878   Value *RHS;
879 
880   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
881       : Pred(Pred), LHS(LHS), RHS(RHS) {}
882 };
883 } // namespace
884 
885 /// Helper function to generate a reproducer function for simplifying \p Cond.
886 /// The reproducer function contains a series of @llvm.assume calls, one for
887 /// each condition in \p Stack. For each condition, the operand instruction are
888 /// cloned until we reach operands that have an entry in \p Value2Index. Those
889 /// will then be added as function arguments. \p DT is used to order cloned
890 /// instructions. The reproducer function will get added to \p M, if it is
891 /// non-null. Otherwise no reproducer function is generated.
892 static void generateReproducer(CmpInst *Cond, Module *M,
893                                ArrayRef<ReproducerEntry> Stack,
894                                ConstraintInfo &Info, DominatorTree &DT) {
895   if (!M)
896     return;
897 
898   LLVMContext &Ctx = Cond->getContext();
899 
900   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
901 
902   ValueToValueMapTy Old2New;
903   SmallVector<Value *> Args;
904   SmallPtrSet<Value *, 8> Seen;
905   // Traverse Cond and its operands recursively until we reach a value that's in
906   // Value2Index or not an instruction, or not a operation that
907   // ConstraintElimination can decompose. Such values will be considered as
908   // external inputs to the reproducer, they are collected and added as function
909   // arguments later.
910   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
911     auto &Value2Index = Info.getValue2Index(IsSigned);
912     SmallVector<Value *, 4> WorkList(Ops);
913     while (!WorkList.empty()) {
914       Value *V = WorkList.pop_back_val();
915       if (!Seen.insert(V).second)
916         continue;
917       if (Old2New.find(V) != Old2New.end())
918         continue;
919       if (isa<Constant>(V))
920         continue;
921 
922       auto *I = dyn_cast<Instruction>(V);
923       if (Value2Index.contains(V) || !I ||
924           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
925         Old2New[V] = V;
926         Args.push_back(V);
927         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
928       } else {
929         append_range(WorkList, I->operands());
930       }
931     }
932   };
933 
934   for (auto &Entry : Stack)
935     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
936       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
937   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
938 
939   SmallVector<Type *> ParamTys;
940   for (auto *P : Args)
941     ParamTys.push_back(P->getType());
942 
943   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
944                                         /*isVarArg=*/false);
945   Function *F = Function::Create(FTy, Function::ExternalLinkage,
946                                  Cond->getModule()->getName() +
947                                      Cond->getFunction()->getName() + "repro",
948                                  M);
949   // Add arguments to the reproducer function for each external value collected.
950   for (unsigned I = 0; I < Args.size(); ++I) {
951     F->getArg(I)->setName(Args[I]->getName());
952     Old2New[Args[I]] = F->getArg(I);
953   }
954 
955   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
956   IRBuilder<> Builder(Entry);
957   Builder.CreateRet(Builder.getTrue());
958   Builder.SetInsertPoint(Entry->getTerminator());
959 
960   // Clone instructions in \p Ops and their operands recursively until reaching
961   // an value in Value2Index (external input to the reproducer). Update Old2New
962   // mapping for the original and cloned instructions. Sort instructions to
963   // clone by dominance, then insert the cloned instructions in the function.
964   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
965     SmallVector<Value *, 4> WorkList(Ops);
966     SmallVector<Instruction *> ToClone;
967     auto &Value2Index = Info.getValue2Index(IsSigned);
968     while (!WorkList.empty()) {
969       Value *V = WorkList.pop_back_val();
970       if (Old2New.find(V) != Old2New.end())
971         continue;
972 
973       auto *I = dyn_cast<Instruction>(V);
974       if (!Value2Index.contains(V) && I) {
975         Old2New[V] = nullptr;
976         ToClone.push_back(I);
977         append_range(WorkList, I->operands());
978       }
979     }
980 
981     sort(ToClone,
982          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
983     for (Instruction *I : ToClone) {
984       Instruction *Cloned = I->clone();
985       Old2New[I] = Cloned;
986       Old2New[I]->setName(I->getName());
987       Cloned->insertBefore(&*Builder.GetInsertPoint());
988       Cloned->dropUnknownNonDebugMetadata();
989       Cloned->setDebugLoc({});
990     }
991   };
992 
993   // Materialize the assumptions for the reproducer using the entries in Stack.
994   // That is, first clone the operands of the condition recursively until we
995   // reach an external input to the reproducer and add them to the reproducer
996   // function. Then add an ICmp for the condition (with the inverse predicate if
997   // the entry is negated) and an assert using the ICmp.
998   for (auto &Entry : Stack) {
999     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1000       continue;
1001 
1002     LLVM_DEBUG(
1003         dbgs() << "  Materializing assumption icmp " << Entry.Pred << ' ';
1004         Entry.LHS->printAsOperand(dbgs(), /*PrintType=*/true); dbgs() << ", ";
1005         Entry.RHS->printAsOperand(dbgs(), /*PrintType=*/false); dbgs() << "\n");
1006     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1007 
1008     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1009     Builder.CreateAssumption(Cmp);
1010   }
1011 
1012   // Finally, clone the condition to reproduce and remap instruction operands in
1013   // the reproducer using Old2New.
1014   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1015   Entry->getTerminator()->setOperand(0, Cond);
1016   remapInstructionsInBlocks({Entry}, Old2New);
1017 
1018   assert(!verifyFunction(*F, &dbgs()));
1019 }
1020 
1021 static std::optional<bool> checkCondition(CmpInst *Cmp, ConstraintInfo &Info,
1022                                           unsigned NumIn, unsigned NumOut,
1023                                           Instruction *ContextInst) {
1024   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
1025 
1026   CmpInst::Predicate Pred = Cmp->getPredicate();
1027   Value *A = Cmp->getOperand(0);
1028   Value *B = Cmp->getOperand(1);
1029 
1030   auto R = Info.getConstraintForSolving(Pred, A, B);
1031   if (R.empty() || !R.isValid(Info)){
1032     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
1033     return std::nullopt;
1034   }
1035 
1036   auto &CSToUse = Info.getCS(R.IsSigned);
1037 
1038   // If there was extra information collected during decomposition, apply
1039   // it now and remove it immediately once we are done with reasoning
1040   // about the constraint.
1041   for (auto &Row : R.ExtraInfo)
1042     CSToUse.addVariableRow(Row);
1043   auto InfoRestorer = make_scope_exit([&]() {
1044     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1045       CSToUse.popLastConstraint();
1046   });
1047 
1048   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1049     if (!DebugCounter::shouldExecute(EliminatedCounter))
1050       return std::nullopt;
1051 
1052     LLVM_DEBUG({
1053       if (*ImpliedCondition) {
1054         dbgs() << "Condition " << *Cmp;
1055       } else {
1056         auto InversePred = Cmp->getInversePredicate();
1057         dbgs() << "Condition " << CmpInst::getPredicateName(InversePred) << " "
1058                << *A << ", " << *B;
1059       }
1060       dbgs() << " implied by dominating constraints\n";
1061       CSToUse.dump();
1062     });
1063     return ImpliedCondition;
1064   }
1065 
1066   return std::nullopt;
1067 }
1068 
1069 static bool checkAndReplaceCondition(
1070     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1071     Instruction *ContextInst, Module *ReproducerModule,
1072     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT) {
1073   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1074     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1075     Constant *ConstantC = ConstantInt::getBool(
1076         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1077     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1078                                        ContextInst](Use &U) {
1079       auto *UserI = getContextInstForUse(U);
1080       auto *DTN = DT.getNode(UserI->getParent());
1081       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1082         return false;
1083       if (UserI->getParent() == ContextInst->getParent() &&
1084           UserI->comesBefore(ContextInst))
1085         return false;
1086 
1087       // Conditions in an assume trivially simplify to true. Skip uses
1088       // in assume calls to not destroy the available information.
1089       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1090       return !II || II->getIntrinsicID() != Intrinsic::assume;
1091     });
1092     NumCondsRemoved++;
1093     return true;
1094   };
1095 
1096   if (auto ImpliedCondition =
1097           checkCondition(Cmp, Info, NumIn, NumOut, ContextInst))
1098     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1099   return false;
1100 }
1101 
1102 static void
1103 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1104                      Module *ReproducerModule,
1105                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1106                      SmallVectorImpl<StackEntry> &DFSInStack) {
1107   Info.popLastConstraint(E.IsSigned);
1108   // Remove variables in the system that went out of scope.
1109   auto &Mapping = Info.getValue2Index(E.IsSigned);
1110   for (Value *V : E.ValuesToRelease)
1111     Mapping.erase(V);
1112   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1113   DFSInStack.pop_back();
1114   if (ReproducerModule)
1115     ReproducerCondStack.pop_back();
1116 }
1117 
1118 /// Check if the first condition for an AND implies the second.
1119 static bool checkAndSecondOpImpliedByFirst(
1120     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1121     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1122     SmallVectorImpl<StackEntry> &DFSInStack) {
1123   CmpInst::Predicate Pred;
1124   Value *A, *B;
1125   Instruction *And = CB.getContextInst();
1126   if (!match(And->getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1127     return false;
1128 
1129   // Optimistically add fact from first condition.
1130   unsigned OldSize = DFSInStack.size();
1131   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1132   if (OldSize == DFSInStack.size())
1133     return false;
1134 
1135   bool Changed = false;
1136   // Check if the second condition can be simplified now.
1137   if (auto ImpliedCondition =
1138           checkCondition(cast<ICmpInst>(And->getOperand(1)), Info, CB.NumIn,
1139                          CB.NumOut, CB.getContextInst())) {
1140     And->setOperand(1, ConstantInt::getBool(And->getType(), *ImpliedCondition));
1141     Changed = true;
1142   }
1143 
1144   // Remove entries again.
1145   while (OldSize < DFSInStack.size()) {
1146     StackEntry E = DFSInStack.back();
1147     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1148                          DFSInStack);
1149   }
1150   return Changed;
1151 }
1152 
1153 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1154                              unsigned NumIn, unsigned NumOut,
1155                              SmallVectorImpl<StackEntry> &DFSInStack) {
1156   // If the constraint has a pre-condition, skip the constraint if it does not
1157   // hold.
1158   SmallVector<Value *> NewVariables;
1159   auto R = getConstraint(Pred, A, B, NewVariables);
1160 
1161   // TODO: Support non-equality for facts as well.
1162   if (!R.isValid(*this) || R.isNe())
1163     return;
1164 
1165   LLVM_DEBUG(dbgs() << "Adding '" << Pred << " ";
1166              A->printAsOperand(dbgs(), false); dbgs() << ", ";
1167              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
1168   bool Added = false;
1169   auto &CSToUse = getCS(R.IsSigned);
1170   if (R.Coefficients.empty())
1171     return;
1172 
1173   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1174 
1175   // If R has been added to the system, add the new variables and queue it for
1176   // removal once it goes out-of-scope.
1177   if (Added) {
1178     SmallVector<Value *, 2> ValuesToRelease;
1179     auto &Value2Index = getValue2Index(R.IsSigned);
1180     for (Value *V : NewVariables) {
1181       Value2Index.insert({V, Value2Index.size() + 1});
1182       ValuesToRelease.push_back(V);
1183     }
1184 
1185     LLVM_DEBUG({
1186       dbgs() << "  constraint: ";
1187       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1188       dbgs() << "\n";
1189     });
1190 
1191     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1192                             std::move(ValuesToRelease));
1193 
1194     if (R.isEq()) {
1195       // Also add the inverted constraint for equality constraints.
1196       for (auto &Coeff : R.Coefficients)
1197         Coeff *= -1;
1198       CSToUse.addVariableRowFill(R.Coefficients);
1199 
1200       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1201                               SmallVector<Value *, 2>());
1202     }
1203   }
1204 }
1205 
1206 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1207                                    SmallVectorImpl<Instruction *> &ToRemove) {
1208   bool Changed = false;
1209   IRBuilder<> Builder(II->getParent(), II->getIterator());
1210   Value *Sub = nullptr;
1211   for (User *U : make_early_inc_range(II->users())) {
1212     if (match(U, m_ExtractValue<0>(m_Value()))) {
1213       if (!Sub)
1214         Sub = Builder.CreateSub(A, B);
1215       U->replaceAllUsesWith(Sub);
1216       Changed = true;
1217     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1218       U->replaceAllUsesWith(Builder.getFalse());
1219       Changed = true;
1220     } else
1221       continue;
1222 
1223     if (U->use_empty()) {
1224       auto *I = cast<Instruction>(U);
1225       ToRemove.push_back(I);
1226       I->setOperand(0, PoisonValue::get(II->getType()));
1227       Changed = true;
1228     }
1229   }
1230 
1231   if (II->use_empty()) {
1232     II->eraseFromParent();
1233     Changed = true;
1234   }
1235   return Changed;
1236 }
1237 
1238 static bool
1239 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1240                           SmallVectorImpl<Instruction *> &ToRemove) {
1241   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1242                               ConstraintInfo &Info) {
1243     auto R = Info.getConstraintForSolving(Pred, A, B);
1244     if (R.size() < 2 || !R.isValid(Info))
1245       return false;
1246 
1247     auto &CSToUse = Info.getCS(R.IsSigned);
1248     return CSToUse.isConditionImplied(R.Coefficients);
1249   };
1250 
1251   bool Changed = false;
1252   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1253     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1254     // can be simplified to a regular sub.
1255     Value *A = II->getArgOperand(0);
1256     Value *B = II->getArgOperand(1);
1257     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1258         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1259                            ConstantInt::get(A->getType(), 0), Info))
1260       return false;
1261     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1262   }
1263   return Changed;
1264 }
1265 
1266 static bool eliminateConstraints(Function &F, DominatorTree &DT,
1267                                  OptimizationRemarkEmitter &ORE) {
1268   bool Changed = false;
1269   DT.updateDFSNumbers();
1270   SmallVector<Value *> FunctionArgs;
1271   for (Value &Arg : F.args())
1272     FunctionArgs.push_back(&Arg);
1273   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
1274   State S(DT);
1275   std::unique_ptr<Module> ReproducerModule(
1276       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1277 
1278   // First, collect conditions implied by branches and blocks with their
1279   // Dominator DFS in and out numbers.
1280   for (BasicBlock &BB : F) {
1281     if (!DT.getNode(&BB))
1282       continue;
1283     S.addInfoFor(BB);
1284   }
1285 
1286   // Next, sort worklist by dominance, so that dominating conditions to check
1287   // and facts come before conditions and facts dominated by them. If a
1288   // condition to check and a fact have the same numbers, conditional facts come
1289   // first. Assume facts and checks are ordered according to their relative
1290   // order in the containing basic block. Also make sure conditions with
1291   // constant operands come before conditions without constant operands. This
1292   // increases the effectiveness of the current signed <-> unsigned fact
1293   // transfer logic.
1294   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1295     auto HasNoConstOp = [](const FactOrCheck &B) {
1296       return !isa<ConstantInt>(B.Inst->getOperand(0)) &&
1297              !isa<ConstantInt>(B.Inst->getOperand(1));
1298     };
1299     // If both entries have the same In numbers, conditional facts come first.
1300     // Otherwise use the relative order in the basic block.
1301     if (A.NumIn == B.NumIn) {
1302       if (A.isConditionFact() && B.isConditionFact()) {
1303         bool NoConstOpA = HasNoConstOp(A);
1304         bool NoConstOpB = HasNoConstOp(B);
1305         return NoConstOpA < NoConstOpB;
1306       }
1307       if (A.isConditionFact())
1308         return true;
1309       if (B.isConditionFact())
1310         return false;
1311       auto *InstA = A.getContextInst();
1312       auto *InstB = B.getContextInst();
1313       return InstA->comesBefore(InstB);
1314     }
1315     return A.NumIn < B.NumIn;
1316   });
1317 
1318   SmallVector<Instruction *> ToRemove;
1319 
1320   // Finally, process ordered worklist and eliminate implied conditions.
1321   SmallVector<StackEntry, 16> DFSInStack;
1322   SmallVector<ReproducerEntry> ReproducerCondStack;
1323   for (FactOrCheck &CB : S.WorkList) {
1324     // First, pop entries from the stack that are out-of-scope for CB. Remove
1325     // the corresponding entry from the constraint system.
1326     while (!DFSInStack.empty()) {
1327       auto &E = DFSInStack.back();
1328       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1329                         << "\n");
1330       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1331       assert(E.NumIn <= CB.NumIn);
1332       if (CB.NumOut <= E.NumOut)
1333         break;
1334       LLVM_DEBUG({
1335         dbgs() << "Removing ";
1336         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1337                        Info.getValue2Index(E.IsSigned));
1338         dbgs() << "\n";
1339       });
1340       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1341                            DFSInStack);
1342     }
1343 
1344     LLVM_DEBUG(dbgs() << "Processing ");
1345 
1346     // For a block, check if any CmpInsts become known based on the current set
1347     // of constraints.
1348     if (CB.isCheck()) {
1349       Instruction *Inst = CB.getInstructionToSimplify();
1350       if (!Inst)
1351         continue;
1352       LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n");
1353       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1354         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1355       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1356         bool Simplified = checkAndReplaceCondition(
1357             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1358             ReproducerModule.get(), ReproducerCondStack, S.DT);
1359         if (!Simplified && match(CB.getContextInst(),
1360                                  m_LogicalAnd(m_Value(), m_Specific(Inst)))) {
1361           Simplified =
1362               checkAndSecondOpImpliedByFirst(CB, Info, ReproducerModule.get(),
1363                                              ReproducerCondStack, DFSInStack);
1364         }
1365         Changed |= Simplified;
1366       }
1367       continue;
1368     }
1369 
1370     LLVM_DEBUG(dbgs() << "fact to add to the system: " << *CB.Inst << "\n");
1371     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
1372       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1373         LLVM_DEBUG(
1374             dbgs()
1375             << "Skip adding constraint because system has too many rows.\n");
1376         return;
1377       }
1378 
1379       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1380       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1381         ReproducerCondStack.emplace_back(Pred, A, B);
1382 
1383       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1384       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1385         // Add dummy entries to ReproducerCondStack to keep it in sync with
1386         // DFSInStack.
1387         for (unsigned I = 0,
1388                       E = (DFSInStack.size() - ReproducerCondStack.size());
1389              I < E; ++I) {
1390           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1391                                            nullptr, nullptr);
1392         }
1393       }
1394     };
1395 
1396     ICmpInst::Predicate Pred;
1397     if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1398       Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1399       AddFact(Pred, MinMax, MinMax->getLHS());
1400       AddFact(Pred, MinMax, MinMax->getRHS());
1401       continue;
1402     }
1403 
1404     Value *A, *B;
1405     Value *Cmp = CB.Inst;
1406     match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp)));
1407     if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1408       // Use the inverse predicate if required.
1409       if (CB.Not)
1410         Pred = CmpInst::getInversePredicate(Pred);
1411 
1412       AddFact(Pred, A, B);
1413     }
1414   }
1415 
1416   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1417     std::string S;
1418     raw_string_ostream StringS(S);
1419     ReproducerModule->print(StringS, nullptr);
1420     StringS.flush();
1421     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1422     Rem << ore::NV("module") << S;
1423     ORE.emit(Rem);
1424   }
1425 
1426 #ifndef NDEBUG
1427   unsigned SignedEntries =
1428       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1429   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1430          "updates to CS and DFSInStack are out of sync");
1431   assert(Info.getCS(true).size() == SignedEntries &&
1432          "updates to CS and DFSInStack are out of sync");
1433 #endif
1434 
1435   for (Instruction *I : ToRemove)
1436     I->eraseFromParent();
1437   return Changed;
1438 }
1439 
1440 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1441                                                  FunctionAnalysisManager &AM) {
1442   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1443   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1444   if (!eliminateConstraints(F, DT, ORE))
1445     return PreservedAnalyses::all();
1446 
1447   PreservedAnalyses PA;
1448   PA.preserve<DominatorTreeAnalysis>();
1449   PA.preserveSet<CFGAnalyses>();
1450   return PA;
1451 }
1452