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