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