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