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