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