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