xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 359bc5c541ae4b02ad74bb9a9c3cb64e61464a4a)
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/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/DebugCounter.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Transforms/Scalar.h"
35 
36 #include <cmath>
37 #include <string>
38 
39 using namespace llvm;
40 using namespace PatternMatch;
41 
42 #define DEBUG_TYPE "constraint-elimination"
43 
44 STATISTIC(NumCondsRemoved, "Number of instructions removed");
45 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
46               "Controls which conditions are eliminated");
47 
48 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
49 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
50 
51 namespace {
52 
53 class ConstraintInfo;
54 
55 struct StackEntry {
56   unsigned NumIn;
57   unsigned NumOut;
58   bool IsSigned = false;
59   /// Variables that can be removed from the system once the stack entry gets
60   /// removed.
61   SmallVector<Value *, 2> ValuesToRelease;
62 
63   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
64              SmallVector<Value *, 2> ValuesToRelease)
65       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
66         ValuesToRelease(ValuesToRelease) {}
67 };
68 
69 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
70 struct PreconditionTy {
71   CmpInst::Predicate Pred;
72   Value *Op0;
73   Value *Op1;
74 
75   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
76       : Pred(Pred), Op0(Op0), Op1(Op1) {}
77 };
78 
79 struct ConstraintTy {
80   SmallVector<int64_t, 8> Coefficients;
81   SmallVector<PreconditionTy, 2> Preconditions;
82 
83   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
84 
85   bool IsSigned = false;
86   bool IsEq = false;
87 
88   ConstraintTy() = default;
89 
90   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
91       : Coefficients(Coefficients), IsSigned(IsSigned) {}
92 
93   unsigned size() const { return Coefficients.size(); }
94 
95   unsigned empty() const { return Coefficients.empty(); }
96 
97   /// Returns true if all preconditions for this list of constraints are
98   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
99   bool isValid(const ConstraintInfo &Info) const;
100 };
101 
102 /// Wrapper encapsulating separate constraint systems and corresponding value
103 /// mappings for both unsigned and signed information. Facts are added to and
104 /// conditions are checked against the corresponding system depending on the
105 /// signed-ness of their predicates. While the information is kept separate
106 /// based on signed-ness, certain conditions can be transferred between the two
107 /// systems.
108 class ConstraintInfo {
109   DenseMap<Value *, unsigned> UnsignedValue2Index;
110   DenseMap<Value *, unsigned> SignedValue2Index;
111 
112   ConstraintSystem UnsignedCS;
113   ConstraintSystem SignedCS;
114 
115   const DataLayout &DL;
116 
117 public:
118   ConstraintInfo(const DataLayout &DL) : DL(DL) {}
119 
120   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
121     return Signed ? SignedValue2Index : UnsignedValue2Index;
122   }
123   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
124     return Signed ? SignedValue2Index : UnsignedValue2Index;
125   }
126 
127   ConstraintSystem &getCS(bool Signed) {
128     return Signed ? SignedCS : UnsignedCS;
129   }
130   const ConstraintSystem &getCS(bool Signed) const {
131     return Signed ? SignedCS : UnsignedCS;
132   }
133 
134   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
135   void popLastNVariables(bool Signed, unsigned N) {
136     getCS(Signed).popLastNVariables(N);
137   }
138 
139   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
140 
141   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
142                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
143 
144   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
145   /// constraints, using indices from the corresponding constraint system.
146   /// New variables that need to be added to the system are collected in
147   /// \p NewVariables.
148   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
149                              SmallVectorImpl<Value *> &NewVariables) const;
150 
151   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
152   /// constraints using getConstraint. Returns an empty constraint if the result
153   /// cannot be used to query the existing constraint system, e.g. because it
154   /// would require adding new variables. Also tries to convert signed
155   /// predicates to unsigned ones if possible to allow using the unsigned system
156   /// which increases the effectiveness of the signed <-> unsigned transfer
157   /// logic.
158   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
159                                        Value *Op1) const;
160 
161   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
162   /// system if \p Pred is signed/unsigned.
163   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
164                              unsigned NumIn, unsigned NumOut,
165                              SmallVectorImpl<StackEntry> &DFSInStack);
166 };
167 
168 /// Represents a (Coefficient * Variable) entry after IR decomposition.
169 struct DecompEntry {
170   int64_t Coefficient;
171   Value *Variable;
172   /// True if the variable is known positive in the current constraint.
173   bool IsKnownPositive;
174 
175   DecompEntry(int64_t Coefficient, Value *Variable,
176               bool IsKnownPositive = false)
177       : Coefficient(Coefficient), Variable(Variable),
178         IsKnownPositive(IsKnownPositive) {}
179 };
180 
181 } // namespace
182 
183 static SmallVector<DecompEntry, 4>
184 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
185           bool IsSigned, const DataLayout &DL);
186 
187 static bool canUseSExt(ConstantInt *CI) {
188   const APInt &Val = CI->getValue();
189   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
190 }
191 
192 static SmallVector<DecompEntry, 4>
193 decomposeGEP(GetElementPtrInst &GEP,
194              SmallVector<PreconditionTy, 4> &Preconditions, bool IsSigned,
195              const DataLayout &DL) {
196   // Do not reason about pointers where the index size is larger than 64 bits,
197   // as the coefficients used to encode constraints are 64 bit integers.
198   unsigned AS =
199       cast<PointerType>(GEP.getPointerOperand()->getType())->getAddressSpace();
200   if (DL.getIndexSizeInBits(AS) > 64)
201     return {};
202 
203   auto GTI = gep_type_begin(GEP);
204   if (GEP.getNumOperands() != 2 || !GEP.isInBounds() ||
205       isa<ScalableVectorType>(GTI.getIndexedType()))
206     return {{0, nullptr}, {1, &GEP}};
207 
208   int64_t Scale = static_cast<int64_t>(
209       DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
210   // Handle the (gep (gep ....), C) case by incrementing the constant
211   // coefficient of the inner GEP, if C is a constant.
212   auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
213   if (InnerGEP && InnerGEP->getNumOperands() == 2 &&
214       isa<ConstantInt>(GEP.getOperand(1))) {
215     APInt Offset = cast<ConstantInt>(GEP.getOperand(1))->getValue();
216     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
217     Result[0].Coefficient += Scale * Offset.getSExtValue();
218     if (Offset.isNegative()) {
219       // Add pre-condition ensuring the GEP is increasing monotonically and
220       // can be de-composed.
221       Preconditions.emplace_back(
222           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
223           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
224                            -1 * Offset.getSExtValue()));
225     }
226     return Result;
227   }
228 
229   Value *Op0, *Op1;
230   ConstantInt *CI;
231   // If the index is zero-extended, it is guaranteed to be positive.
232   if (match(GEP.getOperand(GEP.getNumOperands() - 1), m_ZExt(m_Value(Op0)))) {
233     if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI))
234       return {{0, nullptr},
235               {1, GEP.getPointerOperand()},
236               {Scale * int64_t(std::pow(int64_t(2), CI->getSExtValue())), Op1}};
237     if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))) &&
238         canUseSExt(CI) && match(Op0, m_NUWAdd(m_Value(), m_Value())))
239       return {{Scale * CI->getSExtValue(), nullptr},
240               {1, GEP.getPointerOperand()},
241               {Scale, Op1}};
242 
243     return {{0, nullptr}, {1, GEP.getPointerOperand()}, {Scale, Op0, true}};
244   }
245 
246   if (match(GEP.getOperand(GEP.getNumOperands() - 1), m_ConstantInt(CI)) &&
247       !CI->isNegative() && canUseSExt(CI))
248     return {{Scale * CI->getSExtValue(), nullptr},
249             {1, GEP.getPointerOperand()}};
250 
251   SmallVector<DecompEntry, 4> Result;
252   if (match(GEP.getOperand(GEP.getNumOperands() - 1),
253             m_NSWShl(m_Value(Op0), m_ConstantInt(CI))) &&
254       canUseSExt(CI))
255     Result = {{0, nullptr},
256               {1, GEP.getPointerOperand()},
257               {Scale * int64_t(std::pow(int64_t(2), CI->getSExtValue())), Op0}};
258   else if (match(GEP.getOperand(GEP.getNumOperands() - 1),
259                  m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))) &&
260            canUseSExt(CI))
261     Result = {{Scale * CI->getSExtValue(), nullptr},
262               {1, GEP.getPointerOperand()},
263               {Scale, Op0}};
264   else {
265     Op0 = GEP.getOperand(GEP.getNumOperands() - 1);
266     Result = {{0, nullptr}, {1, GEP.getPointerOperand()}, {Scale, Op0}};
267   }
268   // If Op0 is signed non-negative, the GEP is increasing monotonically and
269   // can be de-composed.
270   Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
271                              ConstantInt::get(Op0->getType(), 0));
272   return Result;
273 }
274 
275 // Decomposes \p V into a vector of entries of the form { Coefficient, Variable
276 // } where Coefficient * Variable. The sum of the pairs equals \p V.  The first
277 // pair is the constant-factor and X must be nullptr. If the expression cannot
278 // be decomposed, returns an empty vector.
279 static SmallVector<DecompEntry, 4>
280 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
281           bool IsSigned, const DataLayout &DL) {
282 
283   // Decompose \p V used with a signed predicate.
284   if (IsSigned) {
285     if (auto *CI = dyn_cast<ConstantInt>(V)) {
286       if (canUseSExt(CI))
287         return {{CI->getSExtValue(), nullptr}};
288     }
289 
290     return {{0, nullptr}, {1, V}};
291   }
292 
293   if (auto *CI = dyn_cast<ConstantInt>(V)) {
294     if (CI->uge(MaxConstraintValue))
295       return {};
296     return {{int64_t(CI->getZExtValue()), nullptr}};
297   }
298 
299   if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
300     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
301 
302   Value *Op0;
303   bool IsKnownPositive = false;
304   if (match(V, m_ZExt(m_Value(Op0)))) {
305     IsKnownPositive = true;
306     V = Op0;
307   }
308 
309   auto MergeResults = [&Preconditions, IsSigned,
310                        DL](Value *A, Value *B,
311                            bool IsSignedB) -> SmallVector<DecompEntry, 4> {
312     auto ResA = decompose(A, Preconditions, IsSigned, DL);
313     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
314     if (ResA.empty() || ResB.empty())
315       return {};
316     ResA[0].Coefficient += ResB[0].Coefficient;
317     append_range(ResA, drop_begin(ResB));
318     return ResA;
319   };
320   Value *Op1;
321   ConstantInt *CI;
322   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
323     return MergeResults(Op0, Op1, IsSigned);
324   }
325   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
326       canUseSExt(CI)) {
327     Preconditions.emplace_back(
328         CmpInst::ICMP_UGE, Op0,
329         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
330     return MergeResults(Op0, CI, true);
331   }
332 
333   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
334     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
335   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
336     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
337 
338   return {{0, nullptr}, {1, V, IsKnownPositive}};
339 }
340 
341 ConstraintTy
342 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
343                               SmallVectorImpl<Value *> &NewVariables) const {
344   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
345   bool IsEq = false;
346   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
347   switch (Pred) {
348   case CmpInst::ICMP_UGT:
349   case CmpInst::ICMP_UGE:
350   case CmpInst::ICMP_SGT:
351   case CmpInst::ICMP_SGE: {
352     Pred = CmpInst::getSwappedPredicate(Pred);
353     std::swap(Op0, Op1);
354     break;
355   }
356   case CmpInst::ICMP_EQ:
357     if (match(Op1, m_Zero())) {
358       Pred = CmpInst::ICMP_ULE;
359     } else {
360       IsEq = true;
361       Pred = CmpInst::ICMP_ULE;
362     }
363     break;
364   case CmpInst::ICMP_NE:
365     if (!match(Op1, m_Zero()))
366       return {};
367     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
368     std::swap(Op0, Op1);
369     break;
370   default:
371     break;
372   }
373 
374   // Only ULE and ULT predicates are supported at the moment.
375   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
376       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
377     return {};
378 
379   SmallVector<PreconditionTy, 4> Preconditions;
380   bool IsSigned = CmpInst::isSigned(Pred);
381   auto &Value2Index = getValue2Index(IsSigned);
382   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
383                         Preconditions, IsSigned, DL);
384   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
385                         Preconditions, IsSigned, DL);
386   // Skip if decomposing either of the values failed.
387   if (ADec.empty() || BDec.empty())
388     return {};
389 
390   int64_t Offset1 = ADec[0].Coefficient;
391   int64_t Offset2 = BDec[0].Coefficient;
392   Offset1 *= -1;
393 
394   // Create iterator ranges that skip the constant-factor.
395   auto VariablesA = llvm::drop_begin(ADec);
396   auto VariablesB = llvm::drop_begin(BDec);
397 
398   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
399   // new entry to NewVariables.
400   DenseMap<Value *, unsigned> NewIndexMap;
401   auto GetOrAddIndex = [&Value2Index, &NewVariables,
402                         &NewIndexMap](Value *V) -> unsigned {
403     auto V2I = Value2Index.find(V);
404     if (V2I != Value2Index.end())
405       return V2I->second;
406     auto Insert =
407         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
408     if (Insert.second)
409       NewVariables.push_back(V);
410     return Insert.first->second;
411   };
412 
413   // Make sure all variables have entries in Value2Index or NewVariables.
414   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
415     GetOrAddIndex(KV.Variable);
416 
417   // Build result constraint, by first adding all coefficients from A and then
418   // subtracting all coefficients from B.
419   ConstraintTy Res(
420       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
421       IsSigned);
422   // Collect variables that are known to be positive in all uses in the
423   // constraint.
424   DenseMap<Value *, bool> KnownPositiveVariables;
425   Res.IsEq = IsEq;
426   auto &R = Res.Coefficients;
427   for (const auto &KV : VariablesA) {
428     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
429     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
430     I.first->second &= KV.IsKnownPositive;
431   }
432 
433   for (const auto &KV : VariablesB) {
434     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
435     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
436     I.first->second &= KV.IsKnownPositive;
437   }
438 
439   int64_t OffsetSum;
440   if (AddOverflow(Offset1, Offset2, OffsetSum))
441     return {};
442   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
443     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
444       return {};
445   R[0] = OffsetSum;
446   Res.Preconditions = std::move(Preconditions);
447 
448   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
449   // variables.
450   while (!NewVariables.empty()) {
451     int64_t Last = R.back();
452     if (Last != 0)
453       break;
454     R.pop_back();
455     Value *RemovedV = NewVariables.pop_back_val();
456     NewIndexMap.erase(RemovedV);
457   }
458 
459   // Add extra constraints for variables that are known positive.
460   for (auto &KV : KnownPositiveVariables) {
461     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
462                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
463       continue;
464     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
465     C[GetOrAddIndex(KV.first)] = -1;
466     Res.ExtraInfo.push_back(C);
467   }
468   return Res;
469 }
470 
471 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
472                                                      Value *Op0,
473                                                      Value *Op1) const {
474   // If both operands are known to be non-negative, change signed predicates to
475   // unsigned ones. This increases the reasoning effectiveness in combination
476   // with the signed <-> unsigned transfer logic.
477   if (CmpInst::isSigned(Pred) &&
478       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
479       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
480     Pred = CmpInst::getUnsignedPredicate(Pred);
481 
482   SmallVector<Value *> NewVariables;
483   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
484   if (R.IsEq || !NewVariables.empty())
485     return {};
486   return R;
487 }
488 
489 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
490   return Coefficients.size() > 0 &&
491          all_of(Preconditions, [&Info](const PreconditionTy &C) {
492            return Info.doesHold(C.Pred, C.Op0, C.Op1);
493          });
494 }
495 
496 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
497                               Value *B) const {
498   auto R = getConstraintForSolving(Pred, A, B);
499   return R.Preconditions.empty() && !R.empty() &&
500          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
501 }
502 
503 void ConstraintInfo::transferToOtherSystem(
504     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
505     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
506   // Check if we can combine facts from the signed and unsigned systems to
507   // derive additional facts.
508   if (!A->getType()->isIntegerTy())
509     return;
510   // FIXME: This currently depends on the order we add facts. Ideally we
511   // would first add all known facts and only then try to add additional
512   // facts.
513   switch (Pred) {
514   default:
515     break;
516   case CmpInst::ICMP_ULT:
517     //  If B is a signed positive constant, A >=s 0 and A <s B.
518     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
519       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
520               NumOut, DFSInStack);
521       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
522     }
523     break;
524   case CmpInst::ICMP_SLT:
525     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
526       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
527     break;
528   case CmpInst::ICMP_SGT:
529     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
530       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
531               NumOut, DFSInStack);
532     break;
533   case CmpInst::ICMP_SGE:
534     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
535       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
536     }
537     break;
538   }
539 }
540 
541 namespace {
542 /// Represents either a condition that holds on entry to a block or a basic
543 /// block, with their respective Dominator DFS in and out numbers.
544 struct ConstraintOrBlock {
545   unsigned NumIn;
546   unsigned NumOut;
547   bool IsBlock;
548   bool Not;
549   union {
550     BasicBlock *BB;
551     CmpInst *Condition;
552   };
553 
554   ConstraintOrBlock(DomTreeNode *DTN)
555       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
556         BB(DTN->getBlock()) {}
557   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
558       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
559         Not(Not), Condition(Condition) {}
560 };
561 
562 /// Keep state required to build worklist.
563 struct State {
564   DominatorTree &DT;
565   SmallVector<ConstraintOrBlock, 64> WorkList;
566 
567   State(DominatorTree &DT) : DT(DT) {}
568 
569   /// Process block \p BB and add known facts to work-list.
570   void addInfoFor(BasicBlock &BB);
571 
572   /// Returns true if we can add a known condition from BB to its successor
573   /// block Succ. Each predecessor of Succ can either be BB or be dominated
574   /// by Succ (e.g. the case when adding a condition from a pre-header to a
575   /// loop header).
576   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
577     if (BB.getSingleSuccessor()) {
578       assert(BB.getSingleSuccessor() == Succ);
579       return DT.properlyDominates(&BB, Succ);
580     }
581     return any_of(successors(&BB),
582                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
583            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
584              return Pred == &BB || DT.dominates(Succ, Pred);
585            });
586   }
587 };
588 
589 } // namespace
590 
591 #ifndef NDEBUG
592 static void dumpWithNames(const ConstraintSystem &CS,
593                           DenseMap<Value *, unsigned> &Value2Index) {
594   SmallVector<std::string> Names(Value2Index.size(), "");
595   for (auto &KV : Value2Index) {
596     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
597   }
598   CS.dump(Names);
599 }
600 
601 static void dumpWithNames(ArrayRef<int64_t> C,
602                           DenseMap<Value *, unsigned> &Value2Index) {
603   ConstraintSystem CS;
604   CS.addVariableRowFill(C);
605   dumpWithNames(CS, Value2Index);
606 }
607 #endif
608 
609 void State::addInfoFor(BasicBlock &BB) {
610   WorkList.emplace_back(DT.getNode(&BB));
611 
612   // True as long as long as the current instruction is guaranteed to execute.
613   bool GuaranteedToExecute = true;
614   // Scan BB for assume calls.
615   // TODO: also use this scan to queue conditions to simplify, so we can
616   // interleave facts from assumes and conditions to simplify in a single
617   // basic block. And to skip another traversal of each basic block when
618   // simplifying.
619   for (Instruction &I : BB) {
620     Value *Cond;
621     // For now, just handle assumes with a single compare as condition.
622     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
623         isa<ICmpInst>(Cond)) {
624       if (GuaranteedToExecute) {
625         // The assume is guaranteed to execute when BB is entered, hence Cond
626         // holds on entry to BB.
627         WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
628       } else {
629         // Otherwise the condition only holds in the successors.
630         for (BasicBlock *Succ : successors(&BB)) {
631           if (!canAddSuccessor(BB, Succ))
632             continue;
633           WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false);
634         }
635       }
636     }
637     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
638   }
639 
640   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
641   if (!Br || !Br->isConditional())
642     return;
643 
644   Value *Cond = Br->getCondition();
645 
646   // If the condition is a chain of ORs/AND and the successor only has the
647   // current block as predecessor, queue conditions for the successor.
648   Value *Op0, *Op1;
649   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
650       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
651     bool IsOr = match(Cond, m_LogicalOr());
652     bool IsAnd = match(Cond, m_LogicalAnd());
653     // If there's a select that matches both AND and OR, we need to commit to
654     // one of the options. Arbitrarily pick OR.
655     if (IsOr && IsAnd)
656       IsAnd = false;
657 
658     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
659     if (canAddSuccessor(BB, Successor)) {
660       SmallVector<Value *> CondWorkList;
661       SmallPtrSet<Value *, 8> SeenCond;
662       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
663         if (SeenCond.insert(V).second)
664           CondWorkList.push_back(V);
665       };
666       QueueValue(Op1);
667       QueueValue(Op0);
668       while (!CondWorkList.empty()) {
669         Value *Cur = CondWorkList.pop_back_val();
670         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
671           WorkList.emplace_back(DT.getNode(Successor), Cmp, IsOr);
672           continue;
673         }
674         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
675           QueueValue(Op1);
676           QueueValue(Op0);
677           continue;
678         }
679         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
680           QueueValue(Op1);
681           QueueValue(Op0);
682           continue;
683         }
684       }
685     }
686     return;
687   }
688 
689   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
690   if (!CmpI)
691     return;
692   if (canAddSuccessor(BB, Br->getSuccessor(0)))
693     WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
694   if (canAddSuccessor(BB, Br->getSuccessor(1)))
695     WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
696 }
697 
698 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
699                              unsigned NumIn, unsigned NumOut,
700                              SmallVectorImpl<StackEntry> &DFSInStack) {
701   // If the constraint has a pre-condition, skip the constraint if it does not
702   // hold.
703   SmallVector<Value *> NewVariables;
704   auto R = getConstraint(Pred, A, B, NewVariables);
705   if (!R.isValid(*this))
706     return;
707 
708   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
709              A->printAsOperand(dbgs(), false); dbgs() << ", ";
710              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
711   bool Added = false;
712   auto &CSToUse = getCS(R.IsSigned);
713   if (R.Coefficients.empty())
714     return;
715 
716   Added |= CSToUse.addVariableRowFill(R.Coefficients);
717 
718   // If R has been added to the system, add the new variables and queue it for
719   // removal once it goes out-of-scope.
720   if (Added) {
721     SmallVector<Value *, 2> ValuesToRelease;
722     auto &Value2Index = getValue2Index(R.IsSigned);
723     for (Value *V : NewVariables) {
724       Value2Index.insert({V, Value2Index.size() + 1});
725       ValuesToRelease.push_back(V);
726     }
727 
728     LLVM_DEBUG({
729       dbgs() << "  constraint: ";
730       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
731       dbgs() << "\n";
732     });
733 
734     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease);
735 
736     if (R.IsEq) {
737       // Also add the inverted constraint for equality constraints.
738       for (auto &Coeff : R.Coefficients)
739         Coeff *= -1;
740       CSToUse.addVariableRowFill(R.Coefficients);
741 
742       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
743                               SmallVector<Value *, 2>());
744     }
745   }
746 }
747 
748 static bool
749 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
750                           SmallVectorImpl<Instruction *> &ToRemove) {
751   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
752                               ConstraintInfo &Info) {
753     auto R = Info.getConstraintForSolving(Pred, A, B);
754     if (R.size() < 2 || !R.isValid(Info))
755       return false;
756 
757     auto &CSToUse = Info.getCS(R.IsSigned);
758     return CSToUse.isConditionImplied(R.Coefficients);
759   };
760 
761   bool Changed = false;
762   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
763     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
764     // can be simplified to a regular sub.
765     Value *A = II->getArgOperand(0);
766     Value *B = II->getArgOperand(1);
767     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
768         !DoesConditionHold(CmpInst::ICMP_SGE, B,
769                            ConstantInt::get(A->getType(), 0), Info))
770       return false;
771 
772     IRBuilder<> Builder(II->getParent(), II->getIterator());
773     Value *Sub = nullptr;
774     for (User *U : make_early_inc_range(II->users())) {
775       if (match(U, m_ExtractValue<0>(m_Value()))) {
776         if (!Sub)
777           Sub = Builder.CreateSub(A, B);
778         U->replaceAllUsesWith(Sub);
779         Changed = true;
780       } else if (match(U, m_ExtractValue<1>(m_Value()))) {
781         U->replaceAllUsesWith(Builder.getFalse());
782         Changed = true;
783       } else
784         continue;
785 
786       if (U->use_empty()) {
787         auto *I = cast<Instruction>(U);
788         ToRemove.push_back(I);
789         I->setOperand(0, PoisonValue::get(II->getType()));
790         Changed = true;
791       }
792     }
793 
794     if (II->use_empty()) {
795       II->eraseFromParent();
796       Changed = true;
797     }
798   }
799   return Changed;
800 }
801 
802 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
803   bool Changed = false;
804   DT.updateDFSNumbers();
805 
806   ConstraintInfo Info(F.getParent()->getDataLayout());
807   State S(DT);
808 
809   // First, collect conditions implied by branches and blocks with their
810   // Dominator DFS in and out numbers.
811   for (BasicBlock &BB : F) {
812     if (!DT.getNode(&BB))
813       continue;
814     S.addInfoFor(BB);
815   }
816 
817   // Next, sort worklist by dominance, so that dominating blocks and conditions
818   // come before blocks and conditions dominated by them. If a block and a
819   // condition have the same numbers, the condition comes before the block, as
820   // it holds on entry to the block. Also make sure conditions with constant
821   // operands come before conditions without constant operands. This increases
822   // the effectiveness of the current signed <-> unsigned fact transfer logic.
823   stable_sort(
824       S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
825         auto HasNoConstOp = [](const ConstraintOrBlock &B) {
826           return !B.IsBlock && !isa<ConstantInt>(B.Condition->getOperand(0)) &&
827                  !isa<ConstantInt>(B.Condition->getOperand(1));
828         };
829         bool NoConstOpA = HasNoConstOp(A);
830         bool NoConstOpB = HasNoConstOp(B);
831         return std::tie(A.NumIn, A.IsBlock, NoConstOpA) <
832                std::tie(B.NumIn, B.IsBlock, NoConstOpB);
833       });
834 
835   SmallVector<Instruction *> ToRemove;
836 
837   // Finally, process ordered worklist and eliminate implied conditions.
838   SmallVector<StackEntry, 16> DFSInStack;
839   for (ConstraintOrBlock &CB : S.WorkList) {
840     // First, pop entries from the stack that are out-of-scope for CB. Remove
841     // the corresponding entry from the constraint system.
842     while (!DFSInStack.empty()) {
843       auto &E = DFSInStack.back();
844       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
845                         << "\n");
846       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
847       assert(E.NumIn <= CB.NumIn);
848       if (CB.NumOut <= E.NumOut)
849         break;
850       LLVM_DEBUG({
851         dbgs() << "Removing ";
852         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
853                       Info.getValue2Index(E.IsSigned));
854         dbgs() << "\n";
855       });
856 
857       Info.popLastConstraint(E.IsSigned);
858       // Remove variables in the system that went out of scope.
859       auto &Mapping = Info.getValue2Index(E.IsSigned);
860       for (Value *V : E.ValuesToRelease)
861         Mapping.erase(V);
862       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
863       DFSInStack.pop_back();
864     }
865 
866     LLVM_DEBUG({
867       dbgs() << "Processing ";
868       if (CB.IsBlock)
869         dbgs() << *CB.BB;
870       else
871         dbgs() << *CB.Condition;
872       dbgs() << "\n";
873     });
874 
875     // For a block, check if any CmpInsts become known based on the current set
876     // of constraints.
877     if (CB.IsBlock) {
878       for (Instruction &I : make_early_inc_range(*CB.BB)) {
879         if (auto *II = dyn_cast<WithOverflowInst>(&I)) {
880           Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
881           continue;
882         }
883         auto *Cmp = dyn_cast<ICmpInst>(&I);
884         if (!Cmp)
885           continue;
886 
887         LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
888         auto R = Info.getConstraintForSolving(
889             Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1));
890         if (R.empty() || !R.isValid(Info))
891           continue;
892 
893         auto &CSToUse = Info.getCS(R.IsSigned);
894 
895         // If there was extra information collected during decomposition, apply
896         // it now and remove it immediately once we are done with reasoning
897         // about the constraint.
898         for (auto &Row : R.ExtraInfo)
899           CSToUse.addVariableRow(Row);
900         auto InfoRestorer = make_scope_exit([&]() {
901           for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
902             CSToUse.popLastConstraint();
903         });
904 
905         if (CSToUse.isConditionImplied(R.Coefficients)) {
906           if (!DebugCounter::shouldExecute(EliminatedCounter))
907             continue;
908 
909           LLVM_DEBUG({
910             dbgs() << "Condition " << *Cmp
911                    << " implied by dominating constraints\n";
912             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
913           });
914           Cmp->replaceUsesWithIf(
915               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
916                 // Conditions in an assume trivially simplify to true. Skip uses
917                 // in assume calls to not destroy the available information.
918                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
919                 return !II || II->getIntrinsicID() != Intrinsic::assume;
920               });
921           NumCondsRemoved++;
922           Changed = true;
923         }
924         if (CSToUse.isConditionImplied(
925                 ConstraintSystem::negate(R.Coefficients))) {
926           if (!DebugCounter::shouldExecute(EliminatedCounter))
927             continue;
928 
929           LLVM_DEBUG({
930             dbgs() << "Condition !" << *Cmp
931                    << " implied by dominating constraints\n";
932             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
933           });
934           Cmp->replaceAllUsesWith(
935               ConstantInt::getFalse(F.getParent()->getContext()));
936           NumCondsRemoved++;
937           Changed = true;
938         }
939       }
940       continue;
941     }
942 
943     ICmpInst::Predicate Pred;
944     Value *A, *B;
945     if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
946       // Use the inverse predicate if required.
947       if (CB.Not)
948         Pred = CmpInst::getInversePredicate(Pred);
949 
950       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
951       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
952     }
953   }
954 
955 #ifndef NDEBUG
956   unsigned SignedEntries =
957       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
958   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
959          "updates to CS and DFSInStack are out of sync");
960   assert(Info.getCS(true).size() == SignedEntries &&
961          "updates to CS and DFSInStack are out of sync");
962 #endif
963 
964   for (Instruction *I : ToRemove)
965     I->eraseFromParent();
966   return Changed;
967 }
968 
969 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
970                                                  FunctionAnalysisManager &AM) {
971   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
972   if (!eliminateConstraints(F, DT))
973     return PreservedAnalyses::all();
974 
975   PreservedAnalyses PA;
976   PA.preserve<DominatorTreeAnalysis>();
977   PA.preserveSet<CFGAnalyses>();
978   return PA;
979 }
980 
981 namespace {
982 
983 class ConstraintElimination : public FunctionPass {
984 public:
985   static char ID;
986 
987   ConstraintElimination() : FunctionPass(ID) {
988     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
989   }
990 
991   bool runOnFunction(Function &F) override {
992     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
993     return eliminateConstraints(F, DT);
994   }
995 
996   void getAnalysisUsage(AnalysisUsage &AU) const override {
997     AU.setPreservesCFG();
998     AU.addRequired<DominatorTreeWrapperPass>();
999     AU.addPreserved<GlobalsAAWrapperPass>();
1000     AU.addPreserved<DominatorTreeWrapperPass>();
1001   }
1002 };
1003 
1004 } // end anonymous namespace
1005 
1006 char ConstraintElimination::ID = 0;
1007 
1008 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
1009                       "Constraint Elimination", false, false)
1010 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1011 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1012 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
1013                     "Constraint Elimination", false, false)
1014 
1015 FunctionPass *llvm::createConstraintEliminationPass() {
1016   return new ConstraintElimination();
1017 }
1018