xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 74d8628cf7cbf442f37fbc3a7012ed77e8749d3c)
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 // A helper to multiply 2 signed integers where overflowing is allowed.
193 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
194   int64_t Result;
195   MulOverflow(A, B, Result);
196   return Result;
197 }
198 
199 // A helper to add 2 signed integers where overflowing is allowed.
200 static int64_t addWithOverflow(int64_t A, int64_t B) {
201   int64_t Result;
202   AddOverflow(A, B, Result);
203   return Result;
204 }
205 
206 static SmallVector<DecompEntry, 4>
207 decomposeGEP(GetElementPtrInst &GEP,
208              SmallVector<PreconditionTy, 4> &Preconditions, bool IsSigned,
209              const DataLayout &DL) {
210   // Do not reason about pointers where the index size is larger than 64 bits,
211   // as the coefficients used to encode constraints are 64 bit integers.
212   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
213     return {};
214 
215   if (!GEP.isInBounds())
216     return {{0, nullptr}, {1, &GEP}};
217 
218   // Handle the (gep (gep ....), C) case by incrementing the constant
219   // coefficient of the inner GEP, if C is a constant.
220   auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
221   if (InnerGEP && GEP.getNumOperands() == 2 &&
222       isa<ConstantInt>(GEP.getOperand(1))) {
223     APInt Offset = cast<ConstantInt>(GEP.getOperand(1))->getValue();
224     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
225 
226     auto GTI = gep_type_begin(GEP);
227     // Bail out for scalable vectors for now.
228     if (isa<ScalableVectorType>(GTI.getIndexedType()))
229       return {};
230     int64_t Scale = static_cast<int64_t>(
231         DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
232 
233     Result[0].Coefficient =
234         addWithOverflow(Result[0].Coefficient,
235                         multiplyWithOverflow(Scale, Offset.getSExtValue()));
236     if (Offset.isNegative()) {
237       // Add pre-condition ensuring the GEP is increasing monotonically and
238       // can be de-composed.
239       Preconditions.emplace_back(
240           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
241           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
242                            -1 * Offset.getSExtValue()));
243     }
244     return Result;
245   }
246 
247   SmallVector<DecompEntry, 4> Result = {{0, nullptr},
248                                         {1, GEP.getPointerOperand()}};
249   gep_type_iterator GTI = gep_type_begin(GEP);
250   for (User::const_op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
251        ++I, ++GTI) {
252     Value *Index = *I;
253 
254     // Bail out for scalable vectors for now.
255     if (isa<ScalableVectorType>(GTI.getIndexedType()))
256       return {};
257 
258     // Struct indices must be constants (and reference an existing field). Add
259     // them to the constant factor.
260     if (StructType *STy = GTI.getStructTypeOrNull()) {
261       // For a struct, add the member offset.
262       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
263       if (FieldNo == 0)
264         continue;
265 
266       // Add offset to constant factor.
267       Result[0].Coefficient = addWithOverflow(
268           Result[0].Coefficient,
269           int64_t(DL.getStructLayout(STy)->getElementOffset(FieldNo)));
270       continue;
271     }
272 
273     // For an array/pointer, add the element offset, explicitly scaled.
274     unsigned Scale = DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize();
275 
276     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
277     if (IdxResult.empty()) {
278       Result.emplace_back(Scale, Index);
279     } else {
280       for (auto &KV : IdxResult)
281         KV.Coefficient = multiplyWithOverflow(KV.Coefficient, Scale);
282       Result[0].Coefficient += IdxResult[0].Coefficient;
283       append_range(Result, ArrayRef<DecompEntry>(IdxResult).drop_front());
284     }
285     // If Op0 is signed non-negative, the GEP is increasing monotonically and
286     // can be de-composed.
287     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
288       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
289                                  ConstantInt::get(Index->getType(), 0));
290   }
291   return Result;
292 }
293 
294 // Decomposes \p V into a vector of entries of the form { Coefficient, Variable
295 // } where Coefficient * Variable. The sum of the pairs equals \p V.  The first
296 // pair is the constant-factor and X must be nullptr. If the expression cannot
297 // be decomposed, returns an empty vector.
298 static SmallVector<DecompEntry, 4>
299 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
300           bool IsSigned, const DataLayout &DL) {
301 
302   auto MergeResults = [&Preconditions, IsSigned,
303                        &DL](Value *A, Value *B,
304                             bool IsSignedB) -> SmallVector<DecompEntry, 4> {
305     auto ResA = decompose(A, Preconditions, IsSigned, DL);
306     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
307     if (ResA.empty() || ResB.empty())
308       return {};
309     ResA[0].Coefficient += ResB[0].Coefficient;
310     append_range(ResA, drop_begin(ResB));
311     return ResA;
312   };
313 
314   // Decompose \p V used with a signed predicate.
315   if (IsSigned) {
316     if (auto *CI = dyn_cast<ConstantInt>(V)) {
317       if (canUseSExt(CI))
318         return {{CI->getSExtValue(), nullptr}};
319     }
320     Value *Op0;
321     Value *Op1;
322     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
323       return MergeResults(Op0, Op1, IsSigned);
324 
325     return {{0, nullptr}, {1, V}};
326   }
327 
328   if (auto *CI = dyn_cast<ConstantInt>(V)) {
329     if (CI->uge(MaxConstraintValue))
330       return {};
331     return {{int64_t(CI->getZExtValue()), nullptr}};
332   }
333 
334   if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
335     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
336 
337   Value *Op0;
338   bool IsKnownPositive = false;
339   if (match(V, m_ZExt(m_Value(Op0)))) {
340     IsKnownPositive = true;
341     V = Op0;
342   }
343 
344   Value *Op1;
345   ConstantInt *CI;
346   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
347     return MergeResults(Op0, Op1, IsSigned);
348   }
349   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
350     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
351       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
352                                  ConstantInt::get(Op0->getType(), 0));
353     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
354       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
355                                  ConstantInt::get(Op1->getType(), 0));
356 
357     return MergeResults(Op0, Op1, IsSigned);
358   }
359 
360   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
361       canUseSExt(CI)) {
362     Preconditions.emplace_back(
363         CmpInst::ICMP_UGE, Op0,
364         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
365     return MergeResults(Op0, CI, true);
366   }
367 
368   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
369     int64_t Mult = int64_t(std::pow(int64_t(2), CI->getSExtValue()));
370     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
371     for (auto &KV : Result)
372       KV.Coefficient *= Mult;
373     return Result;
374   }
375 
376   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
377       (!CI->isNegative())) {
378     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
379     for (auto &KV : Result)
380       KV.Coefficient *= CI->getSExtValue();
381     return Result;
382   }
383 
384   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
385     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
386   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
387     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
388 
389   return {{0, nullptr}, {1, V, IsKnownPositive}};
390 }
391 
392 ConstraintTy
393 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
394                               SmallVectorImpl<Value *> &NewVariables) const {
395   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
396   bool IsEq = false;
397   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
398   switch (Pred) {
399   case CmpInst::ICMP_UGT:
400   case CmpInst::ICMP_UGE:
401   case CmpInst::ICMP_SGT:
402   case CmpInst::ICMP_SGE: {
403     Pred = CmpInst::getSwappedPredicate(Pred);
404     std::swap(Op0, Op1);
405     break;
406   }
407   case CmpInst::ICMP_EQ:
408     if (match(Op1, m_Zero())) {
409       Pred = CmpInst::ICMP_ULE;
410     } else {
411       IsEq = true;
412       Pred = CmpInst::ICMP_ULE;
413     }
414     break;
415   case CmpInst::ICMP_NE:
416     if (!match(Op1, m_Zero()))
417       return {};
418     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
419     std::swap(Op0, Op1);
420     break;
421   default:
422     break;
423   }
424 
425   // Only ULE and ULT predicates are supported at the moment.
426   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
427       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
428     return {};
429 
430   SmallVector<PreconditionTy, 4> Preconditions;
431   bool IsSigned = CmpInst::isSigned(Pred);
432   auto &Value2Index = getValue2Index(IsSigned);
433   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
434                         Preconditions, IsSigned, DL);
435   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
436                         Preconditions, IsSigned, DL);
437   // Skip if decomposing either of the values failed.
438   if (ADec.empty() || BDec.empty())
439     return {};
440 
441   int64_t Offset1 = ADec[0].Coefficient;
442   int64_t Offset2 = BDec[0].Coefficient;
443   Offset1 *= -1;
444 
445   // Create iterator ranges that skip the constant-factor.
446   auto VariablesA = llvm::drop_begin(ADec);
447   auto VariablesB = llvm::drop_begin(BDec);
448 
449   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
450   // new entry to NewVariables.
451   DenseMap<Value *, unsigned> NewIndexMap;
452   auto GetOrAddIndex = [&Value2Index, &NewVariables,
453                         &NewIndexMap](Value *V) -> unsigned {
454     auto V2I = Value2Index.find(V);
455     if (V2I != Value2Index.end())
456       return V2I->second;
457     auto Insert =
458         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
459     if (Insert.second)
460       NewVariables.push_back(V);
461     return Insert.first->second;
462   };
463 
464   // Make sure all variables have entries in Value2Index or NewVariables.
465   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
466     GetOrAddIndex(KV.Variable);
467 
468   // Build result constraint, by first adding all coefficients from A and then
469   // subtracting all coefficients from B.
470   ConstraintTy Res(
471       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
472       IsSigned);
473   // Collect variables that are known to be positive in all uses in the
474   // constraint.
475   DenseMap<Value *, bool> KnownPositiveVariables;
476   Res.IsEq = IsEq;
477   auto &R = Res.Coefficients;
478   for (const auto &KV : VariablesA) {
479     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
480     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
481     I.first->second &= KV.IsKnownPositive;
482   }
483 
484   for (const auto &KV : VariablesB) {
485     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
486     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
487     I.first->second &= KV.IsKnownPositive;
488   }
489 
490   int64_t OffsetSum;
491   if (AddOverflow(Offset1, Offset2, OffsetSum))
492     return {};
493   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
494     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
495       return {};
496   R[0] = OffsetSum;
497   Res.Preconditions = std::move(Preconditions);
498 
499   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
500   // variables.
501   while (!NewVariables.empty()) {
502     int64_t Last = R.back();
503     if (Last != 0)
504       break;
505     R.pop_back();
506     Value *RemovedV = NewVariables.pop_back_val();
507     NewIndexMap.erase(RemovedV);
508   }
509 
510   // Add extra constraints for variables that are known positive.
511   for (auto &KV : KnownPositiveVariables) {
512     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
513                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
514       continue;
515     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
516     C[GetOrAddIndex(KV.first)] = -1;
517     Res.ExtraInfo.push_back(C);
518   }
519   return Res;
520 }
521 
522 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
523                                                      Value *Op0,
524                                                      Value *Op1) const {
525   // If both operands are known to be non-negative, change signed predicates to
526   // unsigned ones. This increases the reasoning effectiveness in combination
527   // with the signed <-> unsigned transfer logic.
528   if (CmpInst::isSigned(Pred) &&
529       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
530       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
531     Pred = CmpInst::getUnsignedPredicate(Pred);
532 
533   SmallVector<Value *> NewVariables;
534   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
535   if (R.IsEq || !NewVariables.empty())
536     return {};
537   return R;
538 }
539 
540 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
541   return Coefficients.size() > 0 &&
542          all_of(Preconditions, [&Info](const PreconditionTy &C) {
543            return Info.doesHold(C.Pred, C.Op0, C.Op1);
544          });
545 }
546 
547 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
548                               Value *B) const {
549   auto R = getConstraintForSolving(Pred, A, B);
550   return R.Preconditions.empty() && !R.empty() &&
551          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
552 }
553 
554 void ConstraintInfo::transferToOtherSystem(
555     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
556     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
557   // Check if we can combine facts from the signed and unsigned systems to
558   // derive additional facts.
559   if (!A->getType()->isIntegerTy())
560     return;
561   // FIXME: This currently depends on the order we add facts. Ideally we
562   // would first add all known facts and only then try to add additional
563   // facts.
564   switch (Pred) {
565   default:
566     break;
567   case CmpInst::ICMP_ULT:
568     //  If B is a signed positive constant, A >=s 0 and A <s B.
569     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
570       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
571               NumOut, DFSInStack);
572       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
573     }
574     break;
575   case CmpInst::ICMP_SLT:
576     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
577       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
578     break;
579   case CmpInst::ICMP_SGT:
580     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
581       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
582               NumOut, DFSInStack);
583     break;
584   case CmpInst::ICMP_SGE:
585     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
586       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
587     }
588     break;
589   }
590 }
591 
592 namespace {
593 /// Represents either a condition that holds on entry to a block or a basic
594 /// block, with their respective Dominator DFS in and out numbers.
595 struct ConstraintOrBlock {
596   unsigned NumIn;
597   unsigned NumOut;
598   bool IsBlock;
599   bool Not;
600   union {
601     BasicBlock *BB;
602     CmpInst *Condition;
603   };
604 
605   ConstraintOrBlock(DomTreeNode *DTN)
606       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
607         BB(DTN->getBlock()) {}
608   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
609       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
610         Not(Not), Condition(Condition) {}
611 };
612 
613 /// Keep state required to build worklist.
614 struct State {
615   DominatorTree &DT;
616   SmallVector<ConstraintOrBlock, 64> WorkList;
617 
618   State(DominatorTree &DT) : DT(DT) {}
619 
620   /// Process block \p BB and add known facts to work-list.
621   void addInfoFor(BasicBlock &BB);
622 
623   /// Returns true if we can add a known condition from BB to its successor
624   /// block Succ. Each predecessor of Succ can either be BB or be dominated
625   /// by Succ (e.g. the case when adding a condition from a pre-header to a
626   /// loop header).
627   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
628     if (BB.getSingleSuccessor()) {
629       assert(BB.getSingleSuccessor() == Succ);
630       return DT.properlyDominates(&BB, Succ);
631     }
632     return any_of(successors(&BB),
633                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
634            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
635              return Pred == &BB || DT.dominates(Succ, Pred);
636            });
637   }
638 };
639 
640 } // namespace
641 
642 #ifndef NDEBUG
643 static void dumpWithNames(const ConstraintSystem &CS,
644                           DenseMap<Value *, unsigned> &Value2Index) {
645   SmallVector<std::string> Names(Value2Index.size(), "");
646   for (auto &KV : Value2Index) {
647     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
648   }
649   CS.dump(Names);
650 }
651 
652 static void dumpWithNames(ArrayRef<int64_t> C,
653                           DenseMap<Value *, unsigned> &Value2Index) {
654   ConstraintSystem CS;
655   CS.addVariableRowFill(C);
656   dumpWithNames(CS, Value2Index);
657 }
658 #endif
659 
660 void State::addInfoFor(BasicBlock &BB) {
661   WorkList.emplace_back(DT.getNode(&BB));
662 
663   // True as long as long as the current instruction is guaranteed to execute.
664   bool GuaranteedToExecute = true;
665   // Scan BB for assume calls.
666   // TODO: also use this scan to queue conditions to simplify, so we can
667   // interleave facts from assumes and conditions to simplify in a single
668   // basic block. And to skip another traversal of each basic block when
669   // simplifying.
670   for (Instruction &I : BB) {
671     Value *Cond;
672     // For now, just handle assumes with a single compare as condition.
673     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
674         isa<ICmpInst>(Cond)) {
675       if (GuaranteedToExecute) {
676         // The assume is guaranteed to execute when BB is entered, hence Cond
677         // holds on entry to BB.
678         WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
679       } else {
680         // Otherwise the condition only holds in the successors.
681         for (BasicBlock *Succ : successors(&BB)) {
682           if (!canAddSuccessor(BB, Succ))
683             continue;
684           WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false);
685         }
686       }
687     }
688     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
689   }
690 
691   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
692   if (!Br || !Br->isConditional())
693     return;
694 
695   Value *Cond = Br->getCondition();
696 
697   // If the condition is a chain of ORs/AND and the successor only has the
698   // current block as predecessor, queue conditions for the successor.
699   Value *Op0, *Op1;
700   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
701       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
702     bool IsOr = match(Cond, m_LogicalOr());
703     bool IsAnd = match(Cond, m_LogicalAnd());
704     // If there's a select that matches both AND and OR, we need to commit to
705     // one of the options. Arbitrarily pick OR.
706     if (IsOr && IsAnd)
707       IsAnd = false;
708 
709     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
710     if (canAddSuccessor(BB, Successor)) {
711       SmallVector<Value *> CondWorkList;
712       SmallPtrSet<Value *, 8> SeenCond;
713       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
714         if (SeenCond.insert(V).second)
715           CondWorkList.push_back(V);
716       };
717       QueueValue(Op1);
718       QueueValue(Op0);
719       while (!CondWorkList.empty()) {
720         Value *Cur = CondWorkList.pop_back_val();
721         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
722           WorkList.emplace_back(DT.getNode(Successor), Cmp, IsOr);
723           continue;
724         }
725         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
726           QueueValue(Op1);
727           QueueValue(Op0);
728           continue;
729         }
730         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
731           QueueValue(Op1);
732           QueueValue(Op0);
733           continue;
734         }
735       }
736     }
737     return;
738   }
739 
740   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
741   if (!CmpI)
742     return;
743   if (canAddSuccessor(BB, Br->getSuccessor(0)))
744     WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
745   if (canAddSuccessor(BB, Br->getSuccessor(1)))
746     WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
747 }
748 
749 static Constant *getScalarConstOrSplat(ConstantInt *C, Type *Ty) {
750   if (auto *VTy = dyn_cast<FixedVectorType>(Ty))
751     return ConstantVector::getSplat(VTy->getElementCount(), C);
752   return C;
753 }
754 
755 static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info) {
756   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
757 
758   // TODO: Implement splat of boolean value for scalable vectors.
759   if (isa<ScalableVectorType>(Cmp->getType())) {
760     LLVM_DEBUG(dbgs() << "   skipping due to scalable vectors\n");
761     return false;
762   }
763 
764   CmpInst::Predicate Pred = Cmp->getPredicate();
765   Value *A = Cmp->getOperand(0);
766   Value *B = Cmp->getOperand(1);
767 
768   auto R = Info.getConstraintForSolving(Pred, A, B);
769   if (R.empty() || !R.isValid(Info)){
770     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
771     return false;
772   }
773 
774   auto &CSToUse = Info.getCS(R.IsSigned);
775 
776   // If there was extra information collected during decomposition, apply
777   // it now and remove it immediately once we are done with reasoning
778   // about the constraint.
779   for (auto &Row : R.ExtraInfo)
780     CSToUse.addVariableRow(Row);
781   auto InfoRestorer = make_scope_exit([&]() {
782     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
783       CSToUse.popLastConstraint();
784   });
785 
786   bool Changed = false;
787   LLVMContext &Ctx = Cmp->getModule()->getContext();
788   if (CSToUse.isConditionImplied(R.Coefficients)) {
789     if (!DebugCounter::shouldExecute(EliminatedCounter))
790       return false;
791 
792     LLVM_DEBUG({
793       dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n";
794       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
795     });
796     Constant *TrueC =
797         getScalarConstOrSplat(ConstantInt::getTrue(Ctx), Cmp->getType());
798     Cmp->replaceUsesWithIf(TrueC, [](Use &U) {
799       // Conditions in an assume trivially simplify to true. Skip uses
800       // in assume calls to not destroy the available information.
801       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
802       return !II || II->getIntrinsicID() != Intrinsic::assume;
803     });
804     NumCondsRemoved++;
805     Changed = true;
806   }
807   if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) {
808     if (!DebugCounter::shouldExecute(EliminatedCounter))
809       return false;
810 
811     LLVM_DEBUG({
812       dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n";
813       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
814     });
815     Constant *FalseC =
816         getScalarConstOrSplat(ConstantInt::getFalse(Ctx), Cmp->getType());
817     Cmp->replaceAllUsesWith(FalseC);
818     NumCondsRemoved++;
819     Changed = true;
820   }
821   return Changed;
822 }
823 
824 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
825                              unsigned NumIn, unsigned NumOut,
826                              SmallVectorImpl<StackEntry> &DFSInStack) {
827   // If the constraint has a pre-condition, skip the constraint if it does not
828   // hold.
829   SmallVector<Value *> NewVariables;
830   auto R = getConstraint(Pred, A, B, NewVariables);
831   if (!R.isValid(*this))
832     return;
833 
834   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
835              A->printAsOperand(dbgs(), false); dbgs() << ", ";
836              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
837   bool Added = false;
838   auto &CSToUse = getCS(R.IsSigned);
839   if (R.Coefficients.empty())
840     return;
841 
842   Added |= CSToUse.addVariableRowFill(R.Coefficients);
843 
844   // If R has been added to the system, add the new variables and queue it for
845   // removal once it goes out-of-scope.
846   if (Added) {
847     SmallVector<Value *, 2> ValuesToRelease;
848     auto &Value2Index = getValue2Index(R.IsSigned);
849     for (Value *V : NewVariables) {
850       Value2Index.insert({V, Value2Index.size() + 1});
851       ValuesToRelease.push_back(V);
852     }
853 
854     LLVM_DEBUG({
855       dbgs() << "  constraint: ";
856       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
857       dbgs() << "\n";
858     });
859 
860     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease);
861 
862     if (R.IsEq) {
863       // Also add the inverted constraint for equality constraints.
864       for (auto &Coeff : R.Coefficients)
865         Coeff *= -1;
866       CSToUse.addVariableRowFill(R.Coefficients);
867 
868       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
869                               SmallVector<Value *, 2>());
870     }
871   }
872 }
873 
874 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
875                                    SmallVectorImpl<Instruction *> &ToRemove) {
876   bool Changed = false;
877   IRBuilder<> Builder(II->getParent(), II->getIterator());
878   Value *Sub = nullptr;
879   for (User *U : make_early_inc_range(II->users())) {
880     if (match(U, m_ExtractValue<0>(m_Value()))) {
881       if (!Sub)
882         Sub = Builder.CreateSub(A, B);
883       U->replaceAllUsesWith(Sub);
884       Changed = true;
885     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
886       U->replaceAllUsesWith(Builder.getFalse());
887       Changed = true;
888     } else
889       continue;
890 
891     if (U->use_empty()) {
892       auto *I = cast<Instruction>(U);
893       ToRemove.push_back(I);
894       I->setOperand(0, PoisonValue::get(II->getType()));
895       Changed = true;
896     }
897   }
898 
899   if (II->use_empty()) {
900     II->eraseFromParent();
901     Changed = true;
902   }
903   return Changed;
904 }
905 
906 static bool
907 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
908                           SmallVectorImpl<Instruction *> &ToRemove) {
909   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
910                               ConstraintInfo &Info) {
911     auto R = Info.getConstraintForSolving(Pred, A, B);
912     if (R.size() < 2 || !R.isValid(Info))
913       return false;
914 
915     auto &CSToUse = Info.getCS(R.IsSigned);
916     return CSToUse.isConditionImplied(R.Coefficients);
917   };
918 
919   bool Changed = false;
920   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
921     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
922     // can be simplified to a regular sub.
923     Value *A = II->getArgOperand(0);
924     Value *B = II->getArgOperand(1);
925     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
926         !DoesConditionHold(CmpInst::ICMP_SGE, B,
927                            ConstantInt::get(A->getType(), 0), Info))
928       return false;
929     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
930   }
931   return Changed;
932 }
933 
934 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
935   bool Changed = false;
936   DT.updateDFSNumbers();
937 
938   ConstraintInfo Info(F.getParent()->getDataLayout());
939   State S(DT);
940 
941   // First, collect conditions implied by branches and blocks with their
942   // Dominator DFS in and out numbers.
943   for (BasicBlock &BB : F) {
944     if (!DT.getNode(&BB))
945       continue;
946     S.addInfoFor(BB);
947   }
948 
949   // Next, sort worklist by dominance, so that dominating blocks and conditions
950   // come before blocks and conditions dominated by them. If a block and a
951   // condition have the same numbers, the condition comes before the block, as
952   // it holds on entry to the block. Also make sure conditions with constant
953   // operands come before conditions without constant operands. This increases
954   // the effectiveness of the current signed <-> unsigned fact transfer logic.
955   stable_sort(
956       S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
957         auto HasNoConstOp = [](const ConstraintOrBlock &B) {
958           return !B.IsBlock && !isa<ConstantInt>(B.Condition->getOperand(0)) &&
959                  !isa<ConstantInt>(B.Condition->getOperand(1));
960         };
961         bool NoConstOpA = HasNoConstOp(A);
962         bool NoConstOpB = HasNoConstOp(B);
963         return std::tie(A.NumIn, A.IsBlock, NoConstOpA) <
964                std::tie(B.NumIn, B.IsBlock, NoConstOpB);
965       });
966 
967   SmallVector<Instruction *> ToRemove;
968 
969   // Finally, process ordered worklist and eliminate implied conditions.
970   SmallVector<StackEntry, 16> DFSInStack;
971   for (ConstraintOrBlock &CB : S.WorkList) {
972     // First, pop entries from the stack that are out-of-scope for CB. Remove
973     // the corresponding entry from the constraint system.
974     while (!DFSInStack.empty()) {
975       auto &E = DFSInStack.back();
976       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
977                         << "\n");
978       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
979       assert(E.NumIn <= CB.NumIn);
980       if (CB.NumOut <= E.NumOut)
981         break;
982       LLVM_DEBUG({
983         dbgs() << "Removing ";
984         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
985                       Info.getValue2Index(E.IsSigned));
986         dbgs() << "\n";
987       });
988 
989       Info.popLastConstraint(E.IsSigned);
990       // Remove variables in the system that went out of scope.
991       auto &Mapping = Info.getValue2Index(E.IsSigned);
992       for (Value *V : E.ValuesToRelease)
993         Mapping.erase(V);
994       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
995       DFSInStack.pop_back();
996     }
997 
998     LLVM_DEBUG({
999       dbgs() << "Processing ";
1000       if (CB.IsBlock)
1001         dbgs() << *CB.BB;
1002       else
1003         dbgs() << *CB.Condition;
1004       dbgs() << "\n";
1005     });
1006 
1007     // For a block, check if any CmpInsts become known based on the current set
1008     // of constraints.
1009     if (CB.IsBlock) {
1010       for (Instruction &I : make_early_inc_range(*CB.BB)) {
1011         if (auto *II = dyn_cast<WithOverflowInst>(&I)) {
1012           Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1013           continue;
1014         }
1015         auto *Cmp = dyn_cast<ICmpInst>(&I);
1016         if (!Cmp)
1017           continue;
1018 
1019         Changed |= checkAndReplaceCondition(Cmp, Info);
1020       }
1021       continue;
1022     }
1023 
1024     ICmpInst::Predicate Pred;
1025     Value *A, *B;
1026     if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1027       // Use the inverse predicate if required.
1028       if (CB.Not)
1029         Pred = CmpInst::getInversePredicate(Pred);
1030 
1031       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1032       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1033     }
1034   }
1035 
1036 #ifndef NDEBUG
1037   unsigned SignedEntries =
1038       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1039   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1040          "updates to CS and DFSInStack are out of sync");
1041   assert(Info.getCS(true).size() == SignedEntries &&
1042          "updates to CS and DFSInStack are out of sync");
1043 #endif
1044 
1045   for (Instruction *I : ToRemove)
1046     I->eraseFromParent();
1047   return Changed;
1048 }
1049 
1050 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1051                                                  FunctionAnalysisManager &AM) {
1052   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1053   if (!eliminateConstraints(F, DT))
1054     return PreservedAnalyses::all();
1055 
1056   PreservedAnalyses PA;
1057   PA.preserve<DominatorTreeAnalysis>();
1058   PA.preserveSet<CFGAnalyses>();
1059   return PA;
1060 }
1061 
1062 namespace {
1063 
1064 class ConstraintElimination : public FunctionPass {
1065 public:
1066   static char ID;
1067 
1068   ConstraintElimination() : FunctionPass(ID) {
1069     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
1070   }
1071 
1072   bool runOnFunction(Function &F) override {
1073     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1074     return eliminateConstraints(F, DT);
1075   }
1076 
1077   void getAnalysisUsage(AnalysisUsage &AU) const override {
1078     AU.setPreservesCFG();
1079     AU.addRequired<DominatorTreeWrapperPass>();
1080     AU.addPreserved<GlobalsAAWrapperPass>();
1081     AU.addPreserved<DominatorTreeWrapperPass>();
1082   }
1083 };
1084 
1085 } // end anonymous namespace
1086 
1087 char ConstraintElimination::ID = 0;
1088 
1089 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
1090                       "Constraint Elimination", false, false)
1091 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1092 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1093 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
1094                     "Constraint Elimination", false, false)
1095 
1096 FunctionPass *llvm::createConstraintEliminationPass() {
1097   return new ConstraintElimination();
1098 }
1099