xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 542c335159d45f4650383a2bdfb337d9f9b4d1f1)
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/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/DebugCounter.h"
30 #include "llvm/Transforms/Scalar.h"
31 
32 #include <string>
33 
34 using namespace llvm;
35 using namespace PatternMatch;
36 
37 #define DEBUG_TYPE "constraint-elimination"
38 
39 STATISTIC(NumCondsRemoved, "Number of instructions removed");
40 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
41               "Controls which conditions are eliminated");
42 
43 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
44 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
45 
46 namespace {
47 
48 /// Wrapper encapsulating separate constraint systems and corresponding value
49 /// mappings for both unsigned and signed information. Facts are added to and
50 /// conditions are checked against the corresponding system depending on the
51 /// signed-ness of their predicates. While the information is kept separate
52 /// based on signed-ness, certain conditions can be transferred between the two
53 /// systems.
54 class ConstraintInfo {
55   DenseMap<Value *, unsigned> UnsignedValue2Index;
56   DenseMap<Value *, unsigned> SignedValue2Index;
57 
58   ConstraintSystem UnsignedCS;
59   ConstraintSystem SignedCS;
60 
61 public:
62   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
63     return Signed ? SignedValue2Index : UnsignedValue2Index;
64   }
65   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
66     return Signed ? SignedValue2Index : UnsignedValue2Index;
67   }
68 
69   ConstraintSystem &getCS(bool Signed) {
70     return Signed ? SignedCS : UnsignedCS;
71   }
72   const ConstraintSystem &getCS(bool Signed) const {
73     return Signed ? SignedCS : UnsignedCS;
74   }
75 
76   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
77   void popLastNVariables(bool Signed, unsigned N) {
78     getCS(Signed).popLastNVariables(N);
79   }
80 };
81 
82 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
83 struct PreconditionTy {
84   CmpInst::Predicate Pred;
85   Value *Op0;
86   Value *Op1;
87 
88   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
89       : Pred(Pred), Op0(Op0), Op1(Op1) {}
90 };
91 
92 struct ConstraintTy {
93   SmallVector<int64_t, 8> Coefficients;
94   SmallVector<PreconditionTy, 2> Preconditions;
95 
96   bool IsSigned = false;
97   bool IsEq = false;
98 
99   ConstraintTy() = default;
100 
101   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
102       : Coefficients(Coefficients), IsSigned(IsSigned) {}
103 
104   unsigned size() const { return Coefficients.size(); }
105 
106   unsigned empty() const { return Coefficients.empty(); }
107 
108   /// Returns true if any constraint has a non-zero coefficient for any of the
109   /// newly added indices. Zero coefficients for new indices are removed. If it
110   /// returns true, no new variable need to be added to the system.
111   bool needsNewIndices(const DenseMap<Value *, unsigned> &NewIndices) {
112     for (unsigned I = 0; I < NewIndices.size(); ++I) {
113       int64_t Last = Coefficients.pop_back_val();
114       if (Last != 0)
115         return true;
116     }
117     return false;
118   }
119 
120   /// Returns true if all preconditions for this list of constraints are
121   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
122   bool isValid(const ConstraintInfo &Info) const;
123 
124   /// Returns true if there is exactly one constraint in the list and isValid is
125   /// also true.
126   bool isValidSingle(const ConstraintInfo &Info) const {
127     if (size() != 1)
128       return false;
129     return isValid(Info);
130   }
131 };
132 
133 } // namespace
134 
135 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The
136 // sum of the pairs equals \p V.  The first pair is the constant-factor and X
137 // must be nullptr. If the expression cannot be decomposed, returns an empty
138 // vector.
139 static SmallVector<std::pair<int64_t, Value *>, 4>
140 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
141           bool IsSigned) {
142 
143   // Decompose \p V used with a signed predicate.
144   if (IsSigned) {
145     if (auto *CI = dyn_cast<ConstantInt>(V)) {
146       const APInt &Val = CI->getValue();
147       if (Val.sle(MinSignedConstraintValue) || Val.sge(MaxConstraintValue))
148         return {};
149       return {{CI->getSExtValue(), nullptr}};
150     }
151 
152     return {{0, nullptr}, {1, V}};
153   }
154 
155   if (auto *CI = dyn_cast<ConstantInt>(V)) {
156     if (CI->isNegative() || CI->uge(MaxConstraintValue))
157       return {};
158     return {{CI->getSExtValue(), nullptr}};
159   }
160   auto *GEP = dyn_cast<GetElementPtrInst>(V);
161   if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) {
162     Value *Op0, *Op1;
163     ConstantInt *CI;
164 
165     // If the index is zero-extended, it is guaranteed to be positive.
166     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
167               m_ZExt(m_Value(Op0)))) {
168       if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))))
169         return {{0, nullptr},
170                 {1, GEP->getPointerOperand()},
171                 {std::pow(int64_t(2), CI->getSExtValue()), Op1}};
172       if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))))
173         return {{CI->getSExtValue(), nullptr},
174                 {1, GEP->getPointerOperand()},
175                 {1, Op1}};
176       return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
177     }
178 
179     if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) &&
180         !CI->isNegative())
181       return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}};
182 
183     SmallVector<std::pair<int64_t, Value *>, 4> Result;
184     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
185               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))))
186       Result = {{0, nullptr},
187                 {1, GEP->getPointerOperand()},
188                 {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
189     else if (match(GEP->getOperand(GEP->getNumOperands() - 1),
190                    m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))))
191       Result = {{CI->getSExtValue(), nullptr},
192                 {1, GEP->getPointerOperand()},
193                 {1, Op0}};
194     else {
195       Op0 = GEP->getOperand(GEP->getNumOperands() - 1);
196       Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
197     }
198     // If Op0 is signed non-negative, the GEP is increasing monotonically and
199     // can be de-composed.
200     Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
201                                ConstantInt::get(Op0->getType(), 0));
202     return Result;
203   }
204 
205   Value *Op0;
206   if (match(V, m_ZExt(m_Value(Op0))))
207     V = Op0;
208 
209   Value *Op1;
210   ConstantInt *CI;
211   if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))))
212     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
213   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative()) {
214     Preconditions.emplace_back(
215         CmpInst::ICMP_UGE, Op0,
216         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
217     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
218   }
219   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
220     return {{0, nullptr}, {1, Op0}, {1, Op1}};
221 
222   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))))
223     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
224   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
225     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
226 
227   return {{0, nullptr}, {1, V}};
228 }
229 
230 /// Turn a condition \p CmpI into a vector of constraints, using indices from \p
231 /// Value2Index. Additional indices for newly discovered values are added to \p
232 /// NewIndices.
233 static ConstraintTy
234 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
235               const DenseMap<Value *, unsigned> &Value2Index,
236               DenseMap<Value *, unsigned> &NewIndices) {
237   bool IsEq = false;
238   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
239   switch (Pred) {
240   case CmpInst::ICMP_UGT:
241   case CmpInst::ICMP_UGE:
242   case CmpInst::ICMP_SGT:
243   case CmpInst::ICMP_SGE: {
244     Pred = CmpInst::getSwappedPredicate(Pred);
245     std::swap(Op0, Op1);
246     break;
247   }
248   case CmpInst::ICMP_EQ:
249     if (match(Op1, m_Zero())) {
250       Pred = CmpInst::ICMP_ULE;
251     } else {
252       IsEq = true;
253       Pred = CmpInst::ICMP_ULE;
254     }
255     break;
256   case CmpInst::ICMP_NE:
257     if (!match(Op1, m_Zero()))
258       return {};
259     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
260     std::swap(Op0, Op1);
261     break;
262   default:
263     break;
264   }
265 
266   // Only ULE and ULT predicates are supported at the moment.
267   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
268       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
269     return {};
270 
271   SmallVector<PreconditionTy, 4> Preconditions;
272   bool IsSigned = CmpInst::isSigned(Pred);
273   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
274                         Preconditions, IsSigned);
275   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
276                         Preconditions, IsSigned);
277   // Skip if decomposing either of the values failed.
278   if (ADec.empty() || BDec.empty())
279     return {};
280 
281   // Skip trivial constraints without any variables.
282   if (ADec.size() == 1 && BDec.size() == 1)
283     return {};
284 
285   int64_t Offset1 = ADec[0].first;
286   int64_t Offset2 = BDec[0].first;
287   Offset1 *= -1;
288 
289   // Create iterator ranges that skip the constant-factor.
290   auto VariablesA = llvm::drop_begin(ADec);
291   auto VariablesB = llvm::drop_begin(BDec);
292 
293   // First try to look up \p V in Value2Index and NewIndices. Otherwise add a
294   // new entry to NewIndices.
295   auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned {
296     auto V2I = Value2Index.find(V);
297     if (V2I != Value2Index.end())
298       return V2I->second;
299     auto Insert =
300         NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1});
301     return Insert.first->second;
302   };
303 
304   // Make sure all variables have entries in Value2Index or NewIndices.
305   for (const auto &KV :
306        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
307     GetOrAddIndex(KV.second);
308 
309   // Build result constraint, by first adding all coefficients from A and then
310   // subtracting all coefficients from B.
311   ConstraintTy Res(
312       SmallVector<int64_t, 8>(Value2Index.size() + NewIndices.size() + 1, 0),
313       IsSigned);
314   Res.IsEq = IsEq;
315   auto &R = Res.Coefficients;
316   for (const auto &KV : VariablesA)
317     R[GetOrAddIndex(KV.second)] += KV.first;
318 
319   for (const auto &KV : VariablesB)
320     R[GetOrAddIndex(KV.second)] -= KV.first;
321 
322   R[0] = Offset1 + Offset2 +
323          (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT) ? -1 : 0);
324   Res.Preconditions = std::move(Preconditions);
325   return Res;
326 }
327 
328 static ConstraintTy getConstraint(CmpInst *Cmp, ConstraintInfo &Info,
329                                   DenseMap<Value *, unsigned> &NewIndices) {
330   return getConstraint(
331       Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1),
332       Info.getValue2Index(CmpInst::isSigned(Cmp->getPredicate())), NewIndices);
333 }
334 
335 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
336   return Coefficients.size() > 0 &&
337          all_of(Preconditions, [&Info](const PreconditionTy &C) {
338            DenseMap<Value *, unsigned> NewIndices;
339            auto R = getConstraint(
340                C.Pred, C.Op0, C.Op1,
341                Info.getValue2Index(CmpInst::isSigned(C.Pred)), NewIndices);
342            // TODO: properly check NewIndices.
343            return NewIndices.empty() && R.Preconditions.empty() && !R.IsEq &&
344                   R.size() >= 2 &&
345                   Info.getCS(CmpInst::isSigned(C.Pred))
346                       .isConditionImplied(R.Coefficients);
347          });
348 }
349 
350 namespace {
351 /// Represents either a condition that holds on entry to a block or a basic
352 /// block, with their respective Dominator DFS in and out numbers.
353 struct ConstraintOrBlock {
354   unsigned NumIn;
355   unsigned NumOut;
356   bool IsBlock;
357   bool Not;
358   union {
359     BasicBlock *BB;
360     CmpInst *Condition;
361   };
362 
363   ConstraintOrBlock(DomTreeNode *DTN)
364       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
365         BB(DTN->getBlock()) {}
366   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
367       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
368         Not(Not), Condition(Condition) {}
369 };
370 
371 struct StackEntry {
372   unsigned NumIn;
373   unsigned NumOut;
374   Instruction *Condition;
375   bool IsNot;
376   bool IsSigned = false;
377   /// Variables that can be removed from the system once the stack entry gets
378   /// removed.
379   SmallVector<Value *, 2> ValuesToRelease;
380 
381   StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot,
382              bool IsSigned, SmallVector<Value *, 2> ValuesToRelease)
383       : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot),
384         IsSigned(IsSigned), ValuesToRelease(ValuesToRelease) {}
385 };
386 } // namespace
387 
388 #ifndef NDEBUG
389 static void dumpWithNames(ConstraintTy &C,
390                           DenseMap<Value *, unsigned> &Value2Index) {
391   SmallVector<std::string> Names(Value2Index.size(), "");
392   for (auto &KV : Value2Index) {
393     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
394   }
395   ConstraintSystem CS;
396   CS.addVariableRowFill(C.Coefficients);
397   CS.dump(Names);
398 }
399 #endif
400 
401 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
402   bool Changed = false;
403   DT.updateDFSNumbers();
404 
405   ConstraintInfo Info;
406 
407   SmallVector<ConstraintOrBlock, 64> WorkList;
408 
409   // First, collect conditions implied by branches and blocks with their
410   // Dominator DFS in and out numbers.
411   for (BasicBlock &BB : F) {
412     if (!DT.getNode(&BB))
413       continue;
414     WorkList.emplace_back(DT.getNode(&BB));
415 
416     // True as long as long as the current instruction is guaranteed to execute.
417     bool GuaranteedToExecute = true;
418     // Scan BB for assume calls.
419     // TODO: also use this scan to queue conditions to simplify, so we can
420     // interleave facts from assumes and conditions to simplify in a single
421     // basic block. And to skip another traversal of each basic block when
422     // simplifying.
423     for (Instruction &I : BB) {
424       Value *Cond;
425       // For now, just handle assumes with a single compare as condition.
426       if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
427           isa<ICmpInst>(Cond)) {
428         if (GuaranteedToExecute) {
429           // The assume is guaranteed to execute when BB is entered, hence Cond
430           // holds on entry to BB.
431           WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
432         } else {
433           // Otherwise the condition only holds in the successors.
434           for (BasicBlock *Succ : successors(&BB))
435             WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond),
436                                   false);
437         }
438       }
439       GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
440     }
441 
442     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
443     if (!Br || !Br->isConditional())
444       continue;
445 
446     // Returns true if we can add a known condition from BB to its successor
447     // block Succ. Each predecessor of Succ can either be BB or be dominated by
448     // Succ (e.g. the case when adding a condition from a pre-header to a loop
449     // header).
450     auto CanAdd = [&BB, &DT](BasicBlock *Succ) {
451       assert(isa<BranchInst>(BB.getTerminator()));
452       return any_of(successors(&BB),
453                     [Succ](const BasicBlock *S) { return S != Succ; }) &&
454              all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) {
455                return Pred == &BB || DT.dominates(Succ, Pred);
456              });
457     };
458     // If the condition is an OR of 2 compares and the false successor only has
459     // the current block as predecessor, queue both negated conditions for the
460     // false successor.
461     Value *Op0, *Op1;
462     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
463         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
464       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
465       if (CanAdd(FalseSuccessor)) {
466         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0),
467                               true);
468         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1),
469                               true);
470       }
471       continue;
472     }
473 
474     // If the condition is an AND of 2 compares and the true successor only has
475     // the current block as predecessor, queue both conditions for the true
476     // successor.
477     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
478         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
479       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
480       if (CanAdd(TrueSuccessor)) {
481         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0),
482                               false);
483         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1),
484                               false);
485       }
486       continue;
487     }
488 
489     auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
490     if (!CmpI)
491       continue;
492     if (CanAdd(Br->getSuccessor(0)))
493       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
494     if (CanAdd(Br->getSuccessor(1)))
495       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
496   }
497 
498   // Next, sort worklist by dominance, so that dominating blocks and conditions
499   // come before blocks and conditions dominated by them. If a block and a
500   // condition have the same numbers, the condition comes before the block, as
501   // it holds on entry to the block.
502   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
503     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
504   });
505 
506   // Finally, process ordered worklist and eliminate implied conditions.
507   SmallVector<StackEntry, 16> DFSInStack;
508   for (ConstraintOrBlock &CB : WorkList) {
509     // First, pop entries from the stack that are out-of-scope for CB. Remove
510     // the corresponding entry from the constraint system.
511     while (!DFSInStack.empty()) {
512       auto &E = DFSInStack.back();
513       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
514                         << "\n");
515       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
516       assert(E.NumIn <= CB.NumIn);
517       if (CB.NumOut <= E.NumOut)
518         break;
519       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
520                         << "\n");
521       Info.popLastConstraint(E.IsSigned);
522       // Remove variables in the system that went out of scope.
523       auto &Mapping = Info.getValue2Index(E.IsSigned);
524       for (Value *V : E.ValuesToRelease)
525         Mapping.erase(V);
526       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
527       DFSInStack.pop_back();
528     }
529 
530     LLVM_DEBUG({
531       dbgs() << "Processing ";
532       if (CB.IsBlock)
533         dbgs() << *CB.BB;
534       else
535         dbgs() << *CB.Condition;
536       dbgs() << "\n";
537     });
538 
539     // For a block, check if any CmpInsts become known based on the current set
540     // of constraints.
541     if (CB.IsBlock) {
542       for (Instruction &I : *CB.BB) {
543         auto *Cmp = dyn_cast<ICmpInst>(&I);
544         if (!Cmp)
545           continue;
546 
547         DenseMap<Value *, unsigned> NewIndices;
548         auto R = getConstraint(Cmp, Info, NewIndices);
549         if (R.IsEq || R.size() < 2 || R.needsNewIndices(NewIndices) ||
550             !R.isValid(Info))
551           continue;
552 
553         auto &CSToUse = Info.getCS(R.IsSigned);
554         if (CSToUse.isConditionImplied(R.Coefficients)) {
555           if (!DebugCounter::shouldExecute(EliminatedCounter))
556             continue;
557 
558           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
559                             << " implied by dominating constraints\n");
560           LLVM_DEBUG({
561             for (auto &E : reverse(DFSInStack))
562               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
563           });
564           Cmp->replaceUsesWithIf(
565               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
566                 // Conditions in an assume trivially simplify to true. Skip uses
567                 // in assume calls to not destroy the available information.
568                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
569                 return !II || II->getIntrinsicID() != Intrinsic::assume;
570               });
571           NumCondsRemoved++;
572           Changed = true;
573         }
574         if (CSToUse.isConditionImplied(
575                 ConstraintSystem::negate(R.Coefficients))) {
576           if (!DebugCounter::shouldExecute(EliminatedCounter))
577             continue;
578 
579           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
580                             << " implied by dominating constraints\n");
581           LLVM_DEBUG({
582             for (auto &E : reverse(DFSInStack))
583               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
584           });
585           Cmp->replaceAllUsesWith(
586               ConstantInt::getFalse(F.getParent()->getContext()));
587           NumCondsRemoved++;
588           Changed = true;
589         }
590       }
591       continue;
592     }
593 
594     // Set up a function to restore the predicate at the end of the scope if it
595     // has been negated. Negate the predicate in-place, if required.
596     auto *CI = dyn_cast<ICmpInst>(CB.Condition);
597     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
598       if (CB.Not && CI)
599         CI->setPredicate(CI->getInversePredicate());
600     });
601     if (CB.Not) {
602       if (CI) {
603         CI->setPredicate(CI->getInversePredicate());
604       } else {
605         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
606         continue;
607       }
608     }
609 
610     // Otherwise, add the condition to the system and stack, if we can transform
611     // it into a constraint.
612     DenseMap<Value *, unsigned> NewIndices;
613     auto R = getConstraint(CB.Condition, Info, NewIndices);
614     if (!R.isValid(Info))
615       continue;
616 
617     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
618     bool Added = false;
619     assert(CmpInst::isSigned(CB.Condition->getPredicate()) == R.IsSigned &&
620            "condition and constraint signs must match");
621     auto &CSToUse = Info.getCS(R.IsSigned);
622     if (R.Coefficients.empty())
623       continue;
624 
625     Added |= CSToUse.addVariableRowFill(R.Coefficients);
626 
627     // If R has been added to the system, queue it for removal once it goes
628     // out-of-scope.
629     if (Added) {
630       SmallVector<Value *, 2> ValuesToRelease;
631       for (auto &KV : NewIndices) {
632         Info.getValue2Index(R.IsSigned).insert(KV);
633         ValuesToRelease.push_back(KV.first);
634       }
635 
636       LLVM_DEBUG({
637         dbgs() << "  constraint: ";
638         dumpWithNames(R, Info.getValue2Index(R.IsSigned));
639       });
640 
641       DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not,
642                               R.IsSigned, ValuesToRelease);
643 
644       if (R.IsEq) {
645         // Also add the inverted constraint for equality constraints.
646         for (auto &Coeff : R.Coefficients)
647           Coeff *= -1;
648         CSToUse.addVariableRowFill(R.Coefficients);
649 
650         DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not,
651                                 R.IsSigned, SmallVector<Value *, 2>());
652       }
653     }
654   }
655 
656 #ifndef NDEBUG
657   unsigned SignedEntries =
658       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
659   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
660          "updates to CS and DFSInStack are out of sync");
661   assert(Info.getCS(true).size() == SignedEntries &&
662          "updates to CS and DFSInStack are out of sync");
663 #endif
664 
665   return Changed;
666 }
667 
668 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
669                                                  FunctionAnalysisManager &AM) {
670   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
671   if (!eliminateConstraints(F, DT))
672     return PreservedAnalyses::all();
673 
674   PreservedAnalyses PA;
675   PA.preserve<DominatorTreeAnalysis>();
676   PA.preserveSet<CFGAnalyses>();
677   return PA;
678 }
679 
680 namespace {
681 
682 class ConstraintElimination : public FunctionPass {
683 public:
684   static char ID;
685 
686   ConstraintElimination() : FunctionPass(ID) {
687     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
688   }
689 
690   bool runOnFunction(Function &F) override {
691     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
692     return eliminateConstraints(F, DT);
693   }
694 
695   void getAnalysisUsage(AnalysisUsage &AU) const override {
696     AU.setPreservesCFG();
697     AU.addRequired<DominatorTreeWrapperPass>();
698     AU.addPreserved<GlobalsAAWrapperPass>();
699     AU.addPreserved<DominatorTreeWrapperPass>();
700   }
701 };
702 
703 } // end anonymous namespace
704 
705 char ConstraintElimination::ID = 0;
706 
707 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
708                       "Constraint Elimination", false, false)
709 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
710 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
711 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
712                     "Constraint Elimination", false, false)
713 
714 FunctionPass *llvm::createConstraintEliminationPass() {
715   return new ConstraintElimination();
716 }
717