1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Analysis/VectorUtils.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include <algorithm>
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 #define DEBUG_TYPE "instsimplify"
41 
42 enum { RecursionLimit = 3 };
43 
44 STATISTIC(NumExpand,  "Number of expansions");
45 STATISTIC(NumReassoc, "Number of reassociations");
46 
47 namespace {
48 struct Query {
49   const DataLayout &DL;
50   const TargetLibraryInfo *TLI;
51   const DominatorTree *DT;
52   AssumptionCache *AC;
53   const Instruction *CxtI;
54 
55   Query(const DataLayout &DL, const TargetLibraryInfo *tli,
56         const DominatorTree *dt, AssumptionCache *ac = nullptr,
57         const Instruction *cxti = nullptr)
58       : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
59 };
60 } // end anonymous namespace
61 
62 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
63 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
64                             unsigned);
65 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
66                               const Query &, unsigned);
67 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
68                               unsigned);
69 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
70 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
71 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
72 
73 /// For a boolean type, or a vector of boolean type, return false, or
74 /// a vector with every element false, as appropriate for the type.
75 static Constant *getFalse(Type *Ty) {
76   assert(Ty->getScalarType()->isIntegerTy(1) &&
77          "Expected i1 type or a vector of i1!");
78   return Constant::getNullValue(Ty);
79 }
80 
81 /// For a boolean type, or a vector of boolean type, return true, or
82 /// a vector with every element true, as appropriate for the type.
83 static Constant *getTrue(Type *Ty) {
84   assert(Ty->getScalarType()->isIntegerTy(1) &&
85          "Expected i1 type or a vector of i1!");
86   return Constant::getAllOnesValue(Ty);
87 }
88 
89 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
90 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
91                           Value *RHS) {
92   CmpInst *Cmp = dyn_cast<CmpInst>(V);
93   if (!Cmp)
94     return false;
95   CmpInst::Predicate CPred = Cmp->getPredicate();
96   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
97   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
98     return true;
99   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
100     CRHS == LHS;
101 }
102 
103 /// Does the given value dominate the specified phi node?
104 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
105   Instruction *I = dyn_cast<Instruction>(V);
106   if (!I)
107     // Arguments and constants dominate all instructions.
108     return true;
109 
110   // If we are processing instructions (and/or basic blocks) that have not been
111   // fully added to a function, the parent nodes may still be null. Simply
112   // return the conservative answer in these cases.
113   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
114     return false;
115 
116   // If we have a DominatorTree then do a precise test.
117   if (DT) {
118     if (!DT->isReachableFromEntry(P->getParent()))
119       return true;
120     if (!DT->isReachableFromEntry(I->getParent()))
121       return false;
122     return DT->dominates(I, P);
123   }
124 
125   // Otherwise, if the instruction is in the entry block and is not an invoke,
126   // then it obviously dominates all phi nodes.
127   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
128       !isa<InvokeInst>(I))
129     return true;
130 
131   return false;
132 }
133 
134 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
135 /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
136 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
137 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
138 /// Returns the simplified value, or null if no simplification was performed.
139 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
140                           unsigned OpcToExpand, const Query &Q,
141                           unsigned MaxRecurse) {
142   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
143   // Recursion is always used, so bail out at once if we already hit the limit.
144   if (!MaxRecurse--)
145     return nullptr;
146 
147   // Check whether the expression has the form "(A op' B) op C".
148   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
149     if (Op0->getOpcode() == OpcodeToExpand) {
150       // It does!  Try turning it into "(A op C) op' (B op C)".
151       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
152       // Do "A op C" and "B op C" both simplify?
153       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
154         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
155           // They do! Return "L op' R" if it simplifies or is already available.
156           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
157           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
158                                      && L == B && R == A)) {
159             ++NumExpand;
160             return LHS;
161           }
162           // Otherwise return "L op' R" if it simplifies.
163           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
164             ++NumExpand;
165             return V;
166           }
167         }
168     }
169 
170   // Check whether the expression has the form "A op (B op' C)".
171   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
172     if (Op1->getOpcode() == OpcodeToExpand) {
173       // It does!  Try turning it into "(A op B) op' (A op C)".
174       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
175       // Do "A op B" and "A op C" both simplify?
176       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
177         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
178           // They do! Return "L op' R" if it simplifies or is already available.
179           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
180           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
181                                      && L == C && R == B)) {
182             ++NumExpand;
183             return RHS;
184           }
185           // Otherwise return "L op' R" if it simplifies.
186           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
187             ++NumExpand;
188             return V;
189           }
190         }
191     }
192 
193   return nullptr;
194 }
195 
196 /// Generic simplifications for associative binary operations.
197 /// Returns the simpler value, or null if none was found.
198 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
199                                        const Query &Q, unsigned MaxRecurse) {
200   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
201   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
202 
203   // Recursion is always used, so bail out at once if we already hit the limit.
204   if (!MaxRecurse--)
205     return nullptr;
206 
207   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
208   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
209 
210   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
211   if (Op0 && Op0->getOpcode() == Opcode) {
212     Value *A = Op0->getOperand(0);
213     Value *B = Op0->getOperand(1);
214     Value *C = RHS;
215 
216     // Does "B op C" simplify?
217     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
218       // It does!  Return "A op V" if it simplifies or is already available.
219       // If V equals B then "A op V" is just the LHS.
220       if (V == B) return LHS;
221       // Otherwise return "A op V" if it simplifies.
222       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
223         ++NumReassoc;
224         return W;
225       }
226     }
227   }
228 
229   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
230   if (Op1 && Op1->getOpcode() == Opcode) {
231     Value *A = LHS;
232     Value *B = Op1->getOperand(0);
233     Value *C = Op1->getOperand(1);
234 
235     // Does "A op B" simplify?
236     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
237       // It does!  Return "V op C" if it simplifies or is already available.
238       // If V equals B then "V op C" is just the RHS.
239       if (V == B) return RHS;
240       // Otherwise return "V op C" if it simplifies.
241       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
242         ++NumReassoc;
243         return W;
244       }
245     }
246   }
247 
248   // The remaining transforms require commutativity as well as associativity.
249   if (!Instruction::isCommutative(Opcode))
250     return nullptr;
251 
252   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
253   if (Op0 && Op0->getOpcode() == Opcode) {
254     Value *A = Op0->getOperand(0);
255     Value *B = Op0->getOperand(1);
256     Value *C = RHS;
257 
258     // Does "C op A" simplify?
259     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
260       // It does!  Return "V op B" if it simplifies or is already available.
261       // If V equals A then "V op B" is just the LHS.
262       if (V == A) return LHS;
263       // Otherwise return "V op B" if it simplifies.
264       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
265         ++NumReassoc;
266         return W;
267       }
268     }
269   }
270 
271   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
272   if (Op1 && Op1->getOpcode() == Opcode) {
273     Value *A = LHS;
274     Value *B = Op1->getOperand(0);
275     Value *C = Op1->getOperand(1);
276 
277     // Does "C op A" simplify?
278     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
279       // It does!  Return "B op V" if it simplifies or is already available.
280       // If V equals C then "B op V" is just the RHS.
281       if (V == C) return RHS;
282       // Otherwise return "B op V" if it simplifies.
283       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
284         ++NumReassoc;
285         return W;
286       }
287     }
288   }
289 
290   return nullptr;
291 }
292 
293 /// In the case of a binary operation with a select instruction as an operand,
294 /// try to simplify the binop by seeing whether evaluating it on both branches
295 /// of the select results in the same value. Returns the common value if so,
296 /// otherwise returns null.
297 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
298                                     const Query &Q, unsigned MaxRecurse) {
299   // Recursion is always used, so bail out at once if we already hit the limit.
300   if (!MaxRecurse--)
301     return nullptr;
302 
303   SelectInst *SI;
304   if (isa<SelectInst>(LHS)) {
305     SI = cast<SelectInst>(LHS);
306   } else {
307     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
308     SI = cast<SelectInst>(RHS);
309   }
310 
311   // Evaluate the BinOp on the true and false branches of the select.
312   Value *TV;
313   Value *FV;
314   if (SI == LHS) {
315     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
316     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
317   } else {
318     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
319     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
320   }
321 
322   // If they simplified to the same value, then return the common value.
323   // If they both failed to simplify then return null.
324   if (TV == FV)
325     return TV;
326 
327   // If one branch simplified to undef, return the other one.
328   if (TV && isa<UndefValue>(TV))
329     return FV;
330   if (FV && isa<UndefValue>(FV))
331     return TV;
332 
333   // If applying the operation did not change the true and false select values,
334   // then the result of the binop is the select itself.
335   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
336     return SI;
337 
338   // If one branch simplified and the other did not, and the simplified
339   // value is equal to the unsimplified one, return the simplified value.
340   // For example, select (cond, X, X & Z) & Z -> X & Z.
341   if ((FV && !TV) || (TV && !FV)) {
342     // Check that the simplified value has the form "X op Y" where "op" is the
343     // same as the original operation.
344     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
345     if (Simplified && Simplified->getOpcode() == Opcode) {
346       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
347       // We already know that "op" is the same as for the simplified value.  See
348       // if the operands match too.  If so, return the simplified value.
349       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
350       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
351       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
352       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
353           Simplified->getOperand(1) == UnsimplifiedRHS)
354         return Simplified;
355       if (Simplified->isCommutative() &&
356           Simplified->getOperand(1) == UnsimplifiedLHS &&
357           Simplified->getOperand(0) == UnsimplifiedRHS)
358         return Simplified;
359     }
360   }
361 
362   return nullptr;
363 }
364 
365 /// In the case of a comparison with a select instruction, try to simplify the
366 /// comparison by seeing whether both branches of the select result in the same
367 /// value. Returns the common value if so, otherwise returns null.
368 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
369                                   Value *RHS, const Query &Q,
370                                   unsigned MaxRecurse) {
371   // Recursion is always used, so bail out at once if we already hit the limit.
372   if (!MaxRecurse--)
373     return nullptr;
374 
375   // Make sure the select is on the LHS.
376   if (!isa<SelectInst>(LHS)) {
377     std::swap(LHS, RHS);
378     Pred = CmpInst::getSwappedPredicate(Pred);
379   }
380   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
381   SelectInst *SI = cast<SelectInst>(LHS);
382   Value *Cond = SI->getCondition();
383   Value *TV = SI->getTrueValue();
384   Value *FV = SI->getFalseValue();
385 
386   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
387   // Does "cmp TV, RHS" simplify?
388   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
389   if (TCmp == Cond) {
390     // It not only simplified, it simplified to the select condition.  Replace
391     // it with 'true'.
392     TCmp = getTrue(Cond->getType());
393   } else if (!TCmp) {
394     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
395     // condition then we can replace it with 'true'.  Otherwise give up.
396     if (!isSameCompare(Cond, Pred, TV, RHS))
397       return nullptr;
398     TCmp = getTrue(Cond->getType());
399   }
400 
401   // Does "cmp FV, RHS" simplify?
402   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
403   if (FCmp == Cond) {
404     // It not only simplified, it simplified to the select condition.  Replace
405     // it with 'false'.
406     FCmp = getFalse(Cond->getType());
407   } else if (!FCmp) {
408     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
409     // condition then we can replace it with 'false'.  Otherwise give up.
410     if (!isSameCompare(Cond, Pred, FV, RHS))
411       return nullptr;
412     FCmp = getFalse(Cond->getType());
413   }
414 
415   // If both sides simplified to the same value, then use it as the result of
416   // the original comparison.
417   if (TCmp == FCmp)
418     return TCmp;
419 
420   // The remaining cases only make sense if the select condition has the same
421   // type as the result of the comparison, so bail out if this is not so.
422   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
423     return nullptr;
424   // If the false value simplified to false, then the result of the compare
425   // is equal to "Cond && TCmp".  This also catches the case when the false
426   // value simplified to false and the true value to true, returning "Cond".
427   if (match(FCmp, m_Zero()))
428     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
429       return V;
430   // If the true value simplified to true, then the result of the compare
431   // is equal to "Cond || FCmp".
432   if (match(TCmp, m_One()))
433     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
434       return V;
435   // Finally, if the false value simplified to true and the true value to
436   // false, then the result of the compare is equal to "!Cond".
437   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
438     if (Value *V =
439         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
440                         Q, MaxRecurse))
441       return V;
442 
443   return nullptr;
444 }
445 
446 /// In the case of a binary operation with an operand that is a PHI instruction,
447 /// try to simplify the binop by seeing whether evaluating it on the incoming
448 /// phi values yields the same result for every value. If so returns the common
449 /// value, otherwise returns null.
450 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
451                                  const Query &Q, unsigned MaxRecurse) {
452   // Recursion is always used, so bail out at once if we already hit the limit.
453   if (!MaxRecurse--)
454     return nullptr;
455 
456   PHINode *PI;
457   if (isa<PHINode>(LHS)) {
458     PI = cast<PHINode>(LHS);
459     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
460     if (!ValueDominatesPHI(RHS, PI, Q.DT))
461       return nullptr;
462   } else {
463     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
464     PI = cast<PHINode>(RHS);
465     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
466     if (!ValueDominatesPHI(LHS, PI, Q.DT))
467       return nullptr;
468   }
469 
470   // Evaluate the BinOp on the incoming phi values.
471   Value *CommonValue = nullptr;
472   for (Value *Incoming : PI->incoming_values()) {
473     // If the incoming value is the phi node itself, it can safely be skipped.
474     if (Incoming == PI) continue;
475     Value *V = PI == LHS ?
476       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
477       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
478     // If the operation failed to simplify, or simplified to a different value
479     // to previously, then give up.
480     if (!V || (CommonValue && V != CommonValue))
481       return nullptr;
482     CommonValue = V;
483   }
484 
485   return CommonValue;
486 }
487 
488 /// In the case of a comparison with a PHI instruction, try to simplify the
489 /// comparison by seeing whether comparing with all of the incoming phi values
490 /// yields the same result every time. If so returns the common result,
491 /// otherwise returns null.
492 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
493                                const Query &Q, unsigned MaxRecurse) {
494   // Recursion is always used, so bail out at once if we already hit the limit.
495   if (!MaxRecurse--)
496     return nullptr;
497 
498   // Make sure the phi is on the LHS.
499   if (!isa<PHINode>(LHS)) {
500     std::swap(LHS, RHS);
501     Pred = CmpInst::getSwappedPredicate(Pred);
502   }
503   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
504   PHINode *PI = cast<PHINode>(LHS);
505 
506   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
507   if (!ValueDominatesPHI(RHS, PI, Q.DT))
508     return nullptr;
509 
510   // Evaluate the BinOp on the incoming phi values.
511   Value *CommonValue = nullptr;
512   for (Value *Incoming : PI->incoming_values()) {
513     // If the incoming value is the phi node itself, it can safely be skipped.
514     if (Incoming == PI) continue;
515     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
516     // If the operation failed to simplify, or simplified to a different value
517     // to previously, then give up.
518     if (!V || (CommonValue && V != CommonValue))
519       return nullptr;
520     CommonValue = V;
521   }
522 
523   return CommonValue;
524 }
525 
526 /// Given operands for an Add, see if we can fold the result.
527 /// If not, this returns null.
528 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
529                               const Query &Q, unsigned MaxRecurse) {
530   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
531     if (Constant *CRHS = dyn_cast<Constant>(Op1))
532       return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
533 
534     // Canonicalize the constant to the RHS.
535     std::swap(Op0, Op1);
536   }
537 
538   // X + undef -> undef
539   if (match(Op1, m_Undef()))
540     return Op1;
541 
542   // X + 0 -> X
543   if (match(Op1, m_Zero()))
544     return Op0;
545 
546   // X + (Y - X) -> Y
547   // (Y - X) + X -> Y
548   // Eg: X + -X -> 0
549   Value *Y = nullptr;
550   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
551       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
552     return Y;
553 
554   // X + ~X -> -1   since   ~X = -X-1
555   if (match(Op0, m_Not(m_Specific(Op1))) ||
556       match(Op1, m_Not(m_Specific(Op0))))
557     return Constant::getAllOnesValue(Op0->getType());
558 
559   /// i1 add -> xor.
560   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
561     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
562       return V;
563 
564   // Try some generic simplifications for associative operations.
565   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
566                                           MaxRecurse))
567     return V;
568 
569   // Threading Add over selects and phi nodes is pointless, so don't bother.
570   // Threading over the select in "A + select(cond, B, C)" means evaluating
571   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
572   // only if B and C are equal.  If B and C are equal then (since we assume
573   // that operands have already been simplified) "select(cond, B, C)" should
574   // have been simplified to the common value of B and C already.  Analysing
575   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
576   // for threading over phi nodes.
577 
578   return nullptr;
579 }
580 
581 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
582                              const DataLayout &DL, const TargetLibraryInfo *TLI,
583                              const DominatorTree *DT, AssumptionCache *AC,
584                              const Instruction *CxtI) {
585   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
586                            RecursionLimit);
587 }
588 
589 /// \brief Compute the base pointer and cumulative constant offsets for V.
590 ///
591 /// This strips all constant offsets off of V, leaving it the base pointer, and
592 /// accumulates the total constant offset applied in the returned constant. It
593 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
594 /// no constant offsets applied.
595 ///
596 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
597 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
598 /// folding.
599 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
600                                                 bool AllowNonInbounds = false) {
601   assert(V->getType()->getScalarType()->isPointerTy());
602 
603   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
604   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
605 
606   // Even though we don't look through PHI nodes, we could be called on an
607   // instruction in an unreachable block, which may be on a cycle.
608   SmallPtrSet<Value *, 4> Visited;
609   Visited.insert(V);
610   do {
611     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
612       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
613           !GEP->accumulateConstantOffset(DL, Offset))
614         break;
615       V = GEP->getPointerOperand();
616     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
617       V = cast<Operator>(V)->getOperand(0);
618     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
619       if (GA->isInterposable())
620         break;
621       V = GA->getAliasee();
622     } else {
623       break;
624     }
625     assert(V->getType()->getScalarType()->isPointerTy() &&
626            "Unexpected operand type!");
627   } while (Visited.insert(V).second);
628 
629   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
630   if (V->getType()->isVectorTy())
631     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
632                                     OffsetIntPtr);
633   return OffsetIntPtr;
634 }
635 
636 /// \brief Compute the constant difference between two pointer values.
637 /// If the difference is not a constant, returns zero.
638 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
639                                           Value *RHS) {
640   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
641   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
642 
643   // If LHS and RHS are not related via constant offsets to the same base
644   // value, there is nothing we can do here.
645   if (LHS != RHS)
646     return nullptr;
647 
648   // Otherwise, the difference of LHS - RHS can be computed as:
649   //    LHS - RHS
650   //  = (LHSOffset + Base) - (RHSOffset + Base)
651   //  = LHSOffset - RHSOffset
652   return ConstantExpr::getSub(LHSOffset, RHSOffset);
653 }
654 
655 /// Given operands for a Sub, see if we can fold the result.
656 /// If not, this returns null.
657 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
658                               const Query &Q, unsigned MaxRecurse) {
659   if (Constant *CLHS = dyn_cast<Constant>(Op0))
660     if (Constant *CRHS = dyn_cast<Constant>(Op1))
661       return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
662 
663   // X - undef -> undef
664   // undef - X -> undef
665   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
666     return UndefValue::get(Op0->getType());
667 
668   // X - 0 -> X
669   if (match(Op1, m_Zero()))
670     return Op0;
671 
672   // X - X -> 0
673   if (Op0 == Op1)
674     return Constant::getNullValue(Op0->getType());
675 
676   // 0 - X -> 0 if the sub is NUW.
677   if (isNUW && match(Op0, m_Zero()))
678     return Op0;
679 
680   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
681   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
682   Value *X = nullptr, *Y = nullptr, *Z = Op1;
683   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
684     // See if "V === Y - Z" simplifies.
685     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
686       // It does!  Now see if "X + V" simplifies.
687       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
688         // It does, we successfully reassociated!
689         ++NumReassoc;
690         return W;
691       }
692     // See if "V === X - Z" simplifies.
693     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
694       // It does!  Now see if "Y + V" simplifies.
695       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
696         // It does, we successfully reassociated!
697         ++NumReassoc;
698         return W;
699       }
700   }
701 
702   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
703   // For example, X - (X + 1) -> -1
704   X = Op0;
705   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
706     // See if "V === X - Y" simplifies.
707     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
708       // It does!  Now see if "V - Z" simplifies.
709       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
710         // It does, we successfully reassociated!
711         ++NumReassoc;
712         return W;
713       }
714     // See if "V === X - Z" simplifies.
715     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
716       // It does!  Now see if "V - Y" simplifies.
717       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
718         // It does, we successfully reassociated!
719         ++NumReassoc;
720         return W;
721       }
722   }
723 
724   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
725   // For example, X - (X - Y) -> Y.
726   Z = Op0;
727   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
728     // See if "V === Z - X" simplifies.
729     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
730       // It does!  Now see if "V + Y" simplifies.
731       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
732         // It does, we successfully reassociated!
733         ++NumReassoc;
734         return W;
735       }
736 
737   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
738   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
739       match(Op1, m_Trunc(m_Value(Y))))
740     if (X->getType() == Y->getType())
741       // See if "V === X - Y" simplifies.
742       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
743         // It does!  Now see if "trunc V" simplifies.
744         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
745           // It does, return the simplified "trunc V".
746           return W;
747 
748   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
749   if (match(Op0, m_PtrToInt(m_Value(X))) &&
750       match(Op1, m_PtrToInt(m_Value(Y))))
751     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
752       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
753 
754   // i1 sub -> xor.
755   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
756     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
757       return V;
758 
759   // Threading Sub over selects and phi nodes is pointless, so don't bother.
760   // Threading over the select in "A - select(cond, B, C)" means evaluating
761   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
762   // only if B and C are equal.  If B and C are equal then (since we assume
763   // that operands have already been simplified) "select(cond, B, C)" should
764   // have been simplified to the common value of B and C already.  Analysing
765   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
766   // for threading over phi nodes.
767 
768   return nullptr;
769 }
770 
771 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
772                              const DataLayout &DL, const TargetLibraryInfo *TLI,
773                              const DominatorTree *DT, AssumptionCache *AC,
774                              const Instruction *CxtI) {
775   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
776                            RecursionLimit);
777 }
778 
779 /// Given operands for an FAdd, see if we can fold the result.  If not, this
780 /// returns null.
781 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
782                               const Query &Q, unsigned MaxRecurse) {
783   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
784     if (Constant *CRHS = dyn_cast<Constant>(Op1))
785       return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
786 
787     // Canonicalize the constant to the RHS.
788     std::swap(Op0, Op1);
789   }
790 
791   // fadd X, -0 ==> X
792   if (match(Op1, m_NegZero()))
793     return Op0;
794 
795   // fadd X, 0 ==> X, when we know X is not -0
796   if (match(Op1, m_Zero()) &&
797       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
798     return Op0;
799 
800   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
801   //   where nnan and ninf have to occur at least once somewhere in this
802   //   expression
803   Value *SubOp = nullptr;
804   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
805     SubOp = Op1;
806   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
807     SubOp = Op0;
808   if (SubOp) {
809     Instruction *FSub = cast<Instruction>(SubOp);
810     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
811         (FMF.noInfs() || FSub->hasNoInfs()))
812       return Constant::getNullValue(Op0->getType());
813   }
814 
815   return nullptr;
816 }
817 
818 /// Given operands for an FSub, see if we can fold the result.  If not, this
819 /// returns null.
820 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
821                               const Query &Q, unsigned MaxRecurse) {
822   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
823     if (Constant *CRHS = dyn_cast<Constant>(Op1))
824       return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
825   }
826 
827   // fsub X, 0 ==> X
828   if (match(Op1, m_Zero()))
829     return Op0;
830 
831   // fsub X, -0 ==> X, when we know X is not -0
832   if (match(Op1, m_NegZero()) &&
833       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
834     return Op0;
835 
836   // fsub -0.0, (fsub -0.0, X) ==> X
837   Value *X;
838   if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
839     return X;
840 
841   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
842   if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
843       match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
844     return X;
845 
846   // fsub nnan x, x ==> 0.0
847   if (FMF.noNaNs() && Op0 == Op1)
848     return Constant::getNullValue(Op0->getType());
849 
850   return nullptr;
851 }
852 
853 /// Given the operands for an FMul, see if we can fold the result
854 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
855                                FastMathFlags FMF,
856                                const Query &Q,
857                                unsigned MaxRecurse) {
858  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
859     if (Constant *CRHS = dyn_cast<Constant>(Op1))
860       return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
861 
862     // Canonicalize the constant to the RHS.
863     std::swap(Op0, Op1);
864  }
865 
866  // fmul X, 1.0 ==> X
867  if (match(Op1, m_FPOne()))
868    return Op0;
869 
870  // fmul nnan nsz X, 0 ==> 0
871  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
872    return Op1;
873 
874  return nullptr;
875 }
876 
877 /// Given operands for a Mul, see if we can fold the result.
878 /// If not, this returns null.
879 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
880                               unsigned MaxRecurse) {
881   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
882     if (Constant *CRHS = dyn_cast<Constant>(Op1))
883       return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
884 
885     // Canonicalize the constant to the RHS.
886     std::swap(Op0, Op1);
887   }
888 
889   // X * undef -> 0
890   if (match(Op1, m_Undef()))
891     return Constant::getNullValue(Op0->getType());
892 
893   // X * 0 -> 0
894   if (match(Op1, m_Zero()))
895     return Op1;
896 
897   // X * 1 -> X
898   if (match(Op1, m_One()))
899     return Op0;
900 
901   // (X / Y) * Y -> X if the division is exact.
902   Value *X = nullptr;
903   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
904       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
905     return X;
906 
907   // i1 mul -> and.
908   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
909     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
910       return V;
911 
912   // Try some generic simplifications for associative operations.
913   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
914                                           MaxRecurse))
915     return V;
916 
917   // Mul distributes over Add.  Try some generic simplifications based on this.
918   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
919                              Q, MaxRecurse))
920     return V;
921 
922   // If the operation is with the result of a select instruction, check whether
923   // operating on either branch of the select always yields the same value.
924   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
925     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
926                                          MaxRecurse))
927       return V;
928 
929   // If the operation is with the result of a phi instruction, check whether
930   // operating on all incoming values of the phi always yields the same value.
931   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
932     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
933                                       MaxRecurse))
934       return V;
935 
936   return nullptr;
937 }
938 
939 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
940                               const DataLayout &DL,
941                               const TargetLibraryInfo *TLI,
942                               const DominatorTree *DT, AssumptionCache *AC,
943                               const Instruction *CxtI) {
944   return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
945                             RecursionLimit);
946 }
947 
948 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
949                               const DataLayout &DL,
950                               const TargetLibraryInfo *TLI,
951                               const DominatorTree *DT, AssumptionCache *AC,
952                               const Instruction *CxtI) {
953   return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
954                             RecursionLimit);
955 }
956 
957 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
958                               const DataLayout &DL,
959                               const TargetLibraryInfo *TLI,
960                               const DominatorTree *DT, AssumptionCache *AC,
961                               const Instruction *CxtI) {
962   return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
963                             RecursionLimit);
964 }
965 
966 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
967                              const TargetLibraryInfo *TLI,
968                              const DominatorTree *DT, AssumptionCache *AC,
969                              const Instruction *CxtI) {
970   return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
971                            RecursionLimit);
972 }
973 
974 /// Given operands for an SDiv or UDiv, see if we can fold the result.
975 /// If not, this returns null.
976 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
977                           const Query &Q, unsigned MaxRecurse) {
978   if (Constant *C0 = dyn_cast<Constant>(Op0))
979     if (Constant *C1 = dyn_cast<Constant>(Op1))
980       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
981 
982   bool isSigned = Opcode == Instruction::SDiv;
983 
984   // X / undef -> undef
985   if (match(Op1, m_Undef()))
986     return Op1;
987 
988   // X / 0 -> undef, we don't need to preserve faults!
989   if (match(Op1, m_Zero()))
990     return UndefValue::get(Op1->getType());
991 
992   // undef / X -> 0
993   if (match(Op0, m_Undef()))
994     return Constant::getNullValue(Op0->getType());
995 
996   // 0 / X -> 0, we don't need to preserve faults!
997   if (match(Op0, m_Zero()))
998     return Op0;
999 
1000   // X / 1 -> X
1001   if (match(Op1, m_One()))
1002     return Op0;
1003 
1004   if (Op0->getType()->isIntegerTy(1))
1005     // It can't be division by zero, hence it must be division by one.
1006     return Op0;
1007 
1008   // X / X -> 1
1009   if (Op0 == Op1)
1010     return ConstantInt::get(Op0->getType(), 1);
1011 
1012   // (X * Y) / Y -> X if the multiplication does not overflow.
1013   Value *X = nullptr, *Y = nullptr;
1014   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1015     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1016     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1017     // If the Mul knows it does not overflow, then we are good to go.
1018     if ((isSigned && Mul->hasNoSignedWrap()) ||
1019         (!isSigned && Mul->hasNoUnsignedWrap()))
1020       return X;
1021     // If X has the form X = A / Y then X * Y cannot overflow.
1022     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1023       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1024         return X;
1025   }
1026 
1027   // (X rem Y) / Y -> 0
1028   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1029       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1030     return Constant::getNullValue(Op0->getType());
1031 
1032   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1033   ConstantInt *C1, *C2;
1034   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1035       match(Op1, m_ConstantInt(C2))) {
1036     bool Overflow;
1037     C1->getValue().umul_ov(C2->getValue(), Overflow);
1038     if (Overflow)
1039       return Constant::getNullValue(Op0->getType());
1040   }
1041 
1042   // If the operation is with the result of a select instruction, check whether
1043   // operating on either branch of the select always yields the same value.
1044   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1045     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1046       return V;
1047 
1048   // If the operation is with the result of a phi instruction, check whether
1049   // operating on all incoming values of the phi always yields the same value.
1050   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1051     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1052       return V;
1053 
1054   return nullptr;
1055 }
1056 
1057 /// Given operands for an SDiv, see if we can fold the result.
1058 /// If not, this returns null.
1059 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1060                                unsigned MaxRecurse) {
1061   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1062     return V;
1063 
1064   return nullptr;
1065 }
1066 
1067 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1068                               const TargetLibraryInfo *TLI,
1069                               const DominatorTree *DT, AssumptionCache *AC,
1070                               const Instruction *CxtI) {
1071   return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1072                             RecursionLimit);
1073 }
1074 
1075 /// Given operands for a UDiv, see if we can fold the result.
1076 /// If not, this returns null.
1077 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1078                                unsigned MaxRecurse) {
1079   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1080     return V;
1081 
1082   return nullptr;
1083 }
1084 
1085 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1086                               const TargetLibraryInfo *TLI,
1087                               const DominatorTree *DT, AssumptionCache *AC,
1088                               const Instruction *CxtI) {
1089   return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1090                             RecursionLimit);
1091 }
1092 
1093 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1094                                const Query &Q, unsigned) {
1095   // undef / X -> undef    (the undef could be a snan).
1096   if (match(Op0, m_Undef()))
1097     return Op0;
1098 
1099   // X / undef -> undef
1100   if (match(Op1, m_Undef()))
1101     return Op1;
1102 
1103   // 0 / X -> 0
1104   // Requires that NaNs are off (X could be zero) and signed zeroes are
1105   // ignored (X could be positive or negative, so the output sign is unknown).
1106   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1107     return Op0;
1108 
1109   if (FMF.noNaNs()) {
1110     // X / X -> 1.0 is legal when NaNs are ignored.
1111     if (Op0 == Op1)
1112       return ConstantFP::get(Op0->getType(), 1.0);
1113 
1114     // -X /  X -> -1.0 and
1115     //  X / -X -> -1.0 are legal when NaNs are ignored.
1116     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1117     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1118          BinaryOperator::getFNegArgument(Op0) == Op1) ||
1119         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1120          BinaryOperator::getFNegArgument(Op1) == Op0))
1121       return ConstantFP::get(Op0->getType(), -1.0);
1122   }
1123 
1124   return nullptr;
1125 }
1126 
1127 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1128                               const DataLayout &DL,
1129                               const TargetLibraryInfo *TLI,
1130                               const DominatorTree *DT, AssumptionCache *AC,
1131                               const Instruction *CxtI) {
1132   return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1133                             RecursionLimit);
1134 }
1135 
1136 /// Given operands for an SRem or URem, see if we can fold the result.
1137 /// If not, this returns null.
1138 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1139                           const Query &Q, unsigned MaxRecurse) {
1140   if (Constant *C0 = dyn_cast<Constant>(Op0))
1141     if (Constant *C1 = dyn_cast<Constant>(Op1))
1142       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1143 
1144   // X % undef -> undef
1145   if (match(Op1, m_Undef()))
1146     return Op1;
1147 
1148   // undef % X -> 0
1149   if (match(Op0, m_Undef()))
1150     return Constant::getNullValue(Op0->getType());
1151 
1152   // 0 % X -> 0, we don't need to preserve faults!
1153   if (match(Op0, m_Zero()))
1154     return Op0;
1155 
1156   // X % 0 -> undef, we don't need to preserve faults!
1157   if (match(Op1, m_Zero()))
1158     return UndefValue::get(Op0->getType());
1159 
1160   // X % 1 -> 0
1161   if (match(Op1, m_One()))
1162     return Constant::getNullValue(Op0->getType());
1163 
1164   if (Op0->getType()->isIntegerTy(1))
1165     // It can't be remainder by zero, hence it must be remainder by one.
1166     return Constant::getNullValue(Op0->getType());
1167 
1168   // X % X -> 0
1169   if (Op0 == Op1)
1170     return Constant::getNullValue(Op0->getType());
1171 
1172   // (X % Y) % Y -> X % Y
1173   if ((Opcode == Instruction::SRem &&
1174        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1175       (Opcode == Instruction::URem &&
1176        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1177     return Op0;
1178 
1179   // If the operation is with the result of a select instruction, check whether
1180   // operating on either branch of the select always yields the same value.
1181   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1182     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1183       return V;
1184 
1185   // If the operation is with the result of a phi instruction, check whether
1186   // operating on all incoming values of the phi always yields the same value.
1187   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1188     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1189       return V;
1190 
1191   return nullptr;
1192 }
1193 
1194 /// Given operands for an SRem, see if we can fold the result.
1195 /// If not, this returns null.
1196 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1197                                unsigned MaxRecurse) {
1198   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1199     return V;
1200 
1201   return nullptr;
1202 }
1203 
1204 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1205                               const TargetLibraryInfo *TLI,
1206                               const DominatorTree *DT, AssumptionCache *AC,
1207                               const Instruction *CxtI) {
1208   return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1209                             RecursionLimit);
1210 }
1211 
1212 /// Given operands for a URem, see if we can fold the result.
1213 /// If not, this returns null.
1214 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1215                                unsigned MaxRecurse) {
1216   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1217     return V;
1218 
1219   return nullptr;
1220 }
1221 
1222 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1223                               const TargetLibraryInfo *TLI,
1224                               const DominatorTree *DT, AssumptionCache *AC,
1225                               const Instruction *CxtI) {
1226   return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1227                             RecursionLimit);
1228 }
1229 
1230 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1231                                const Query &, unsigned) {
1232   // undef % X -> undef    (the undef could be a snan).
1233   if (match(Op0, m_Undef()))
1234     return Op0;
1235 
1236   // X % undef -> undef
1237   if (match(Op1, m_Undef()))
1238     return Op1;
1239 
1240   // 0 % X -> 0
1241   // Requires that NaNs are off (X could be zero) and signed zeroes are
1242   // ignored (X could be positive or negative, so the output sign is unknown).
1243   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1244     return Op0;
1245 
1246   return nullptr;
1247 }
1248 
1249 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1250                               const DataLayout &DL,
1251                               const TargetLibraryInfo *TLI,
1252                               const DominatorTree *DT, AssumptionCache *AC,
1253                               const Instruction *CxtI) {
1254   return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1255                             RecursionLimit);
1256 }
1257 
1258 /// Returns true if a shift by \c Amount always yields undef.
1259 static bool isUndefShift(Value *Amount) {
1260   Constant *C = dyn_cast<Constant>(Amount);
1261   if (!C)
1262     return false;
1263 
1264   // X shift by undef -> undef because it may shift by the bitwidth.
1265   if (isa<UndefValue>(C))
1266     return true;
1267 
1268   // Shifting by the bitwidth or more is undefined.
1269   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1270     if (CI->getValue().getLimitedValue() >=
1271         CI->getType()->getScalarSizeInBits())
1272       return true;
1273 
1274   // If all lanes of a vector shift are undefined the whole shift is.
1275   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1276     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1277       if (!isUndefShift(C->getAggregateElement(I)))
1278         return false;
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1286 /// If not, this returns null.
1287 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1288                             const Query &Q, unsigned MaxRecurse) {
1289   if (Constant *C0 = dyn_cast<Constant>(Op0))
1290     if (Constant *C1 = dyn_cast<Constant>(Op1))
1291       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1292 
1293   // 0 shift by X -> 0
1294   if (match(Op0, m_Zero()))
1295     return Op0;
1296 
1297   // X shift by 0 -> X
1298   if (match(Op1, m_Zero()))
1299     return Op0;
1300 
1301   // Fold undefined shifts.
1302   if (isUndefShift(Op1))
1303     return UndefValue::get(Op0->getType());
1304 
1305   // If the operation is with the result of a select instruction, check whether
1306   // operating on either branch of the select always yields the same value.
1307   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1308     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1309       return V;
1310 
1311   // If the operation is with the result of a phi instruction, check whether
1312   // operating on all incoming values of the phi always yields the same value.
1313   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1314     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1315       return V;
1316 
1317   return nullptr;
1318 }
1319 
1320 /// \brief Given operands for an Shl, LShr or AShr, see if we can
1321 /// fold the result.  If not, this returns null.
1322 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1323                                  bool isExact, const Query &Q,
1324                                  unsigned MaxRecurse) {
1325   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1326     return V;
1327 
1328   // X >> X -> 0
1329   if (Op0 == Op1)
1330     return Constant::getNullValue(Op0->getType());
1331 
1332   // undef >> X -> 0
1333   // undef >> X -> undef (if it's exact)
1334   if (match(Op0, m_Undef()))
1335     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1336 
1337   // The low bit cannot be shifted out of an exact shift if it is set.
1338   if (isExact) {
1339     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1340     APInt Op0KnownZero(BitWidth, 0);
1341     APInt Op0KnownOne(BitWidth, 0);
1342     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1343                      Q.CxtI, Q.DT);
1344     if (Op0KnownOne[0])
1345       return Op0;
1346   }
1347 
1348   return nullptr;
1349 }
1350 
1351 /// Given operands for an Shl, see if we can fold the result.
1352 /// If not, this returns null.
1353 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1354                               const Query &Q, unsigned MaxRecurse) {
1355   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1356     return V;
1357 
1358   // undef << X -> 0
1359   // undef << X -> undef if (if it's NSW/NUW)
1360   if (match(Op0, m_Undef()))
1361     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1362 
1363   // (X >> A) << A -> X
1364   Value *X;
1365   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1366     return X;
1367   return nullptr;
1368 }
1369 
1370 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1371                              const DataLayout &DL, const TargetLibraryInfo *TLI,
1372                              const DominatorTree *DT, AssumptionCache *AC,
1373                              const Instruction *CxtI) {
1374   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1375                            RecursionLimit);
1376 }
1377 
1378 /// Given operands for an LShr, see if we can fold the result.
1379 /// If not, this returns null.
1380 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1381                                const Query &Q, unsigned MaxRecurse) {
1382   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1383                                     MaxRecurse))
1384       return V;
1385 
1386   // (X << A) >> A -> X
1387   Value *X;
1388   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1389     return X;
1390 
1391   return nullptr;
1392 }
1393 
1394 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1395                               const DataLayout &DL,
1396                               const TargetLibraryInfo *TLI,
1397                               const DominatorTree *DT, AssumptionCache *AC,
1398                               const Instruction *CxtI) {
1399   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1400                             RecursionLimit);
1401 }
1402 
1403 /// Given operands for an AShr, see if we can fold the result.
1404 /// If not, this returns null.
1405 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1406                                const Query &Q, unsigned MaxRecurse) {
1407   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1408                                     MaxRecurse))
1409     return V;
1410 
1411   // all ones >>a X -> all ones
1412   if (match(Op0, m_AllOnes()))
1413     return Op0;
1414 
1415   // (X << A) >> A -> X
1416   Value *X;
1417   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1418     return X;
1419 
1420   // Arithmetic shifting an all-sign-bit value is a no-op.
1421   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1422   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1423     return Op0;
1424 
1425   return nullptr;
1426 }
1427 
1428 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1429                               const DataLayout &DL,
1430                               const TargetLibraryInfo *TLI,
1431                               const DominatorTree *DT, AssumptionCache *AC,
1432                               const Instruction *CxtI) {
1433   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1434                             RecursionLimit);
1435 }
1436 
1437 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1438                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1439   Value *X, *Y;
1440 
1441   ICmpInst::Predicate EqPred;
1442   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1443       !ICmpInst::isEquality(EqPred))
1444     return nullptr;
1445 
1446   ICmpInst::Predicate UnsignedPred;
1447   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1448       ICmpInst::isUnsigned(UnsignedPred))
1449     ;
1450   else if (match(UnsignedICmp,
1451                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1452            ICmpInst::isUnsigned(UnsignedPred))
1453     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1454   else
1455     return nullptr;
1456 
1457   // X < Y && Y != 0  -->  X < Y
1458   // X < Y || Y != 0  -->  Y != 0
1459   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1460     return IsAnd ? UnsignedICmp : ZeroICmp;
1461 
1462   // X >= Y || Y != 0  -->  true
1463   // X >= Y || Y == 0  -->  X >= Y
1464   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1465     if (EqPred == ICmpInst::ICMP_NE)
1466       return getTrue(UnsignedICmp->getType());
1467     return UnsignedICmp;
1468   }
1469 
1470   // X < Y && Y == 0  -->  false
1471   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1472       IsAnd)
1473     return getFalse(UnsignedICmp->getType());
1474 
1475   return nullptr;
1476 }
1477 
1478 /// Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1479 /// of possible values cannot be satisfied.
1480 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1481   ICmpInst::Predicate Pred0, Pred1;
1482   ConstantInt *CI1, *CI2;
1483   Value *V;
1484 
1485   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1486     return X;
1487 
1488   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1489                          m_ConstantInt(CI2))))
1490    return nullptr;
1491 
1492   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1493     return nullptr;
1494 
1495   Type *ITy = Op0->getType();
1496 
1497   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1498   bool isNSW = AddInst->hasNoSignedWrap();
1499   bool isNUW = AddInst->hasNoUnsignedWrap();
1500 
1501   const APInt &CI1V = CI1->getValue();
1502   const APInt &CI2V = CI2->getValue();
1503   const APInt Delta = CI2V - CI1V;
1504   if (CI1V.isStrictlyPositive()) {
1505     if (Delta == 2) {
1506       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1507         return getFalse(ITy);
1508       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1509         return getFalse(ITy);
1510     }
1511     if (Delta == 1) {
1512       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1513         return getFalse(ITy);
1514       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1515         return getFalse(ITy);
1516     }
1517   }
1518   if (CI1V.getBoolValue() && isNUW) {
1519     if (Delta == 2)
1520       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1521         return getFalse(ITy);
1522     if (Delta == 1)
1523       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1524         return getFalse(ITy);
1525   }
1526 
1527   return nullptr;
1528 }
1529 
1530 /// Given operands for an And, see if we can fold the result.
1531 /// If not, this returns null.
1532 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1533                               unsigned MaxRecurse) {
1534   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1535     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1536       return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1537 
1538     // Canonicalize the constant to the RHS.
1539     std::swap(Op0, Op1);
1540   }
1541 
1542   // X & undef -> 0
1543   if (match(Op1, m_Undef()))
1544     return Constant::getNullValue(Op0->getType());
1545 
1546   // X & X = X
1547   if (Op0 == Op1)
1548     return Op0;
1549 
1550   // X & 0 = 0
1551   if (match(Op1, m_Zero()))
1552     return Op1;
1553 
1554   // X & -1 = X
1555   if (match(Op1, m_AllOnes()))
1556     return Op0;
1557 
1558   // A & ~A  =  ~A & A  =  0
1559   if (match(Op0, m_Not(m_Specific(Op1))) ||
1560       match(Op1, m_Not(m_Specific(Op0))))
1561     return Constant::getNullValue(Op0->getType());
1562 
1563   // (A | ?) & A = A
1564   Value *A = nullptr, *B = nullptr;
1565   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1566       (A == Op1 || B == Op1))
1567     return Op1;
1568 
1569   // A & (A | ?) = A
1570   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1571       (A == Op0 || B == Op0))
1572     return Op0;
1573 
1574   // A & (-A) = A if A is a power of two or zero.
1575   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1576       match(Op1, m_Neg(m_Specific(Op0)))) {
1577     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1578                                Q.DT))
1579       return Op0;
1580     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1581                                Q.DT))
1582       return Op1;
1583   }
1584 
1585   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1586     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1587       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1588         return V;
1589       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1590         return V;
1591     }
1592   }
1593 
1594   // Try some generic simplifications for associative operations.
1595   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1596                                           MaxRecurse))
1597     return V;
1598 
1599   // And distributes over Or.  Try some generic simplifications based on this.
1600   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1601                              Q, MaxRecurse))
1602     return V;
1603 
1604   // And distributes over Xor.  Try some generic simplifications based on this.
1605   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1606                              Q, MaxRecurse))
1607     return V;
1608 
1609   // If the operation is with the result of a select instruction, check whether
1610   // operating on either branch of the select always yields the same value.
1611   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1612     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1613                                          MaxRecurse))
1614       return V;
1615 
1616   // If the operation is with the result of a phi instruction, check whether
1617   // operating on all incoming values of the phi always yields the same value.
1618   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1619     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1620                                       MaxRecurse))
1621       return V;
1622 
1623   return nullptr;
1624 }
1625 
1626 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1627                              const TargetLibraryInfo *TLI,
1628                              const DominatorTree *DT, AssumptionCache *AC,
1629                              const Instruction *CxtI) {
1630   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1631                            RecursionLimit);
1632 }
1633 
1634 /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1635 /// contains all possible values.
1636 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1637   ICmpInst::Predicate Pred0, Pred1;
1638   ConstantInt *CI1, *CI2;
1639   Value *V;
1640 
1641   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1642     return X;
1643 
1644   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1645                          m_ConstantInt(CI2))))
1646    return nullptr;
1647 
1648   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1649     return nullptr;
1650 
1651   Type *ITy = Op0->getType();
1652 
1653   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1654   bool isNSW = AddInst->hasNoSignedWrap();
1655   bool isNUW = AddInst->hasNoUnsignedWrap();
1656 
1657   const APInt &CI1V = CI1->getValue();
1658   const APInt &CI2V = CI2->getValue();
1659   const APInt Delta = CI2V - CI1V;
1660   if (CI1V.isStrictlyPositive()) {
1661     if (Delta == 2) {
1662       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1663         return getTrue(ITy);
1664       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1665         return getTrue(ITy);
1666     }
1667     if (Delta == 1) {
1668       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1669         return getTrue(ITy);
1670       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1671         return getTrue(ITy);
1672     }
1673   }
1674   if (CI1V.getBoolValue() && isNUW) {
1675     if (Delta == 2)
1676       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1677         return getTrue(ITy);
1678     if (Delta == 1)
1679       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1680         return getTrue(ITy);
1681   }
1682 
1683   return nullptr;
1684 }
1685 
1686 /// Given operands for an Or, see if we can fold the result.
1687 /// If not, this returns null.
1688 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1689                              unsigned MaxRecurse) {
1690   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1691     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1692       return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1693 
1694     // Canonicalize the constant to the RHS.
1695     std::swap(Op0, Op1);
1696   }
1697 
1698   // X | undef -> -1
1699   if (match(Op1, m_Undef()))
1700     return Constant::getAllOnesValue(Op0->getType());
1701 
1702   // X | X = X
1703   if (Op0 == Op1)
1704     return Op0;
1705 
1706   // X | 0 = X
1707   if (match(Op1, m_Zero()))
1708     return Op0;
1709 
1710   // X | -1 = -1
1711   if (match(Op1, m_AllOnes()))
1712     return Op1;
1713 
1714   // A | ~A  =  ~A | A  =  -1
1715   if (match(Op0, m_Not(m_Specific(Op1))) ||
1716       match(Op1, m_Not(m_Specific(Op0))))
1717     return Constant::getAllOnesValue(Op0->getType());
1718 
1719   // (A & ?) | A = A
1720   Value *A = nullptr, *B = nullptr;
1721   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1722       (A == Op1 || B == Op1))
1723     return Op1;
1724 
1725   // A | (A & ?) = A
1726   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1727       (A == Op0 || B == Op0))
1728     return Op0;
1729 
1730   // ~(A & ?) | A = -1
1731   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1732       (A == Op1 || B == Op1))
1733     return Constant::getAllOnesValue(Op1->getType());
1734 
1735   // A | ~(A & ?) = -1
1736   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1737       (A == Op0 || B == Op0))
1738     return Constant::getAllOnesValue(Op0->getType());
1739 
1740   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1741     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1742       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1743         return V;
1744       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1745         return V;
1746     }
1747   }
1748 
1749   // Try some generic simplifications for associative operations.
1750   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1751                                           MaxRecurse))
1752     return V;
1753 
1754   // Or distributes over And.  Try some generic simplifications based on this.
1755   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1756                              MaxRecurse))
1757     return V;
1758 
1759   // If the operation is with the result of a select instruction, check whether
1760   // operating on either branch of the select always yields the same value.
1761   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1762     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1763                                          MaxRecurse))
1764       return V;
1765 
1766   // (A & C)|(B & D)
1767   Value *C = nullptr, *D = nullptr;
1768   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1769       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1770     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1771     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1772     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1773       // (A & C1)|(B & C2)
1774       // If we have: ((V + N) & C1) | (V & C2)
1775       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1776       // replace with V+N.
1777       Value *V1, *V2;
1778       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1779           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1780         // Add commutes, try both ways.
1781         if (V1 == B &&
1782             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1783           return A;
1784         if (V2 == B &&
1785             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1786           return A;
1787       }
1788       // Or commutes, try both ways.
1789       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1790           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1791         // Add commutes, try both ways.
1792         if (V1 == A &&
1793             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1794           return B;
1795         if (V2 == A &&
1796             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1797           return B;
1798       }
1799     }
1800   }
1801 
1802   // If the operation is with the result of a phi instruction, check whether
1803   // operating on all incoming values of the phi always yields the same value.
1804   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1805     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1806       return V;
1807 
1808   return nullptr;
1809 }
1810 
1811 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1812                             const TargetLibraryInfo *TLI,
1813                             const DominatorTree *DT, AssumptionCache *AC,
1814                             const Instruction *CxtI) {
1815   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1816                           RecursionLimit);
1817 }
1818 
1819 /// Given operands for a Xor, see if we can fold the result.
1820 /// If not, this returns null.
1821 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1822                               unsigned MaxRecurse) {
1823   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1824     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1825       return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1826 
1827     // Canonicalize the constant to the RHS.
1828     std::swap(Op0, Op1);
1829   }
1830 
1831   // A ^ undef -> undef
1832   if (match(Op1, m_Undef()))
1833     return Op1;
1834 
1835   // A ^ 0 = A
1836   if (match(Op1, m_Zero()))
1837     return Op0;
1838 
1839   // A ^ A = 0
1840   if (Op0 == Op1)
1841     return Constant::getNullValue(Op0->getType());
1842 
1843   // A ^ ~A  =  ~A ^ A  =  -1
1844   if (match(Op0, m_Not(m_Specific(Op1))) ||
1845       match(Op1, m_Not(m_Specific(Op0))))
1846     return Constant::getAllOnesValue(Op0->getType());
1847 
1848   // Try some generic simplifications for associative operations.
1849   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1850                                           MaxRecurse))
1851     return V;
1852 
1853   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1854   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1855   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1856   // only if B and C are equal.  If B and C are equal then (since we assume
1857   // that operands have already been simplified) "select(cond, B, C)" should
1858   // have been simplified to the common value of B and C already.  Analysing
1859   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1860   // for threading over phi nodes.
1861 
1862   return nullptr;
1863 }
1864 
1865 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1866                              const TargetLibraryInfo *TLI,
1867                              const DominatorTree *DT, AssumptionCache *AC,
1868                              const Instruction *CxtI) {
1869   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1870                            RecursionLimit);
1871 }
1872 
1873 static Type *GetCompareTy(Value *Op) {
1874   return CmpInst::makeCmpResultType(Op->getType());
1875 }
1876 
1877 /// Rummage around inside V looking for something equivalent to the comparison
1878 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1879 /// Helper function for analyzing max/min idioms.
1880 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1881                                          Value *LHS, Value *RHS) {
1882   SelectInst *SI = dyn_cast<SelectInst>(V);
1883   if (!SI)
1884     return nullptr;
1885   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1886   if (!Cmp)
1887     return nullptr;
1888   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1889   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1890     return Cmp;
1891   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1892       LHS == CmpRHS && RHS == CmpLHS)
1893     return Cmp;
1894   return nullptr;
1895 }
1896 
1897 // A significant optimization not implemented here is assuming that alloca
1898 // addresses are not equal to incoming argument values. They don't *alias*,
1899 // as we say, but that doesn't mean they aren't equal, so we take a
1900 // conservative approach.
1901 //
1902 // This is inspired in part by C++11 5.10p1:
1903 //   "Two pointers of the same type compare equal if and only if they are both
1904 //    null, both point to the same function, or both represent the same
1905 //    address."
1906 //
1907 // This is pretty permissive.
1908 //
1909 // It's also partly due to C11 6.5.9p6:
1910 //   "Two pointers compare equal if and only if both are null pointers, both are
1911 //    pointers to the same object (including a pointer to an object and a
1912 //    subobject at its beginning) or function, both are pointers to one past the
1913 //    last element of the same array object, or one is a pointer to one past the
1914 //    end of one array object and the other is a pointer to the start of a
1915 //    different array object that happens to immediately follow the first array
1916 //    object in the address space.)
1917 //
1918 // C11's version is more restrictive, however there's no reason why an argument
1919 // couldn't be a one-past-the-end value for a stack object in the caller and be
1920 // equal to the beginning of a stack object in the callee.
1921 //
1922 // If the C and C++ standards are ever made sufficiently restrictive in this
1923 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1924 // this optimization.
1925 static Constant *computePointerICmp(const DataLayout &DL,
1926                                     const TargetLibraryInfo *TLI,
1927                                     CmpInst::Predicate Pred, Value *LHS,
1928                                     Value *RHS) {
1929   // First, skip past any trivial no-ops.
1930   LHS = LHS->stripPointerCasts();
1931   RHS = RHS->stripPointerCasts();
1932 
1933   // A non-null pointer is not equal to a null pointer.
1934   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1935       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1936     return ConstantInt::get(GetCompareTy(LHS),
1937                             !CmpInst::isTrueWhenEqual(Pred));
1938 
1939   // We can only fold certain predicates on pointer comparisons.
1940   switch (Pred) {
1941   default:
1942     return nullptr;
1943 
1944     // Equality comaprisons are easy to fold.
1945   case CmpInst::ICMP_EQ:
1946   case CmpInst::ICMP_NE:
1947     break;
1948 
1949     // We can only handle unsigned relational comparisons because 'inbounds' on
1950     // a GEP only protects against unsigned wrapping.
1951   case CmpInst::ICMP_UGT:
1952   case CmpInst::ICMP_UGE:
1953   case CmpInst::ICMP_ULT:
1954   case CmpInst::ICMP_ULE:
1955     // However, we have to switch them to their signed variants to handle
1956     // negative indices from the base pointer.
1957     Pred = ICmpInst::getSignedPredicate(Pred);
1958     break;
1959   }
1960 
1961   // Strip off any constant offsets so that we can reason about them.
1962   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1963   // here and compare base addresses like AliasAnalysis does, however there are
1964   // numerous hazards. AliasAnalysis and its utilities rely on special rules
1965   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1966   // doesn't need to guarantee pointer inequality when it says NoAlias.
1967   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1968   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1969 
1970   // If LHS and RHS are related via constant offsets to the same base
1971   // value, we can replace it with an icmp which just compares the offsets.
1972   if (LHS == RHS)
1973     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1974 
1975   // Various optimizations for (in)equality comparisons.
1976   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1977     // Different non-empty allocations that exist at the same time have
1978     // different addresses (if the program can tell). Global variables always
1979     // exist, so they always exist during the lifetime of each other and all
1980     // allocas. Two different allocas usually have different addresses...
1981     //
1982     // However, if there's an @llvm.stackrestore dynamically in between two
1983     // allocas, they may have the same address. It's tempting to reduce the
1984     // scope of the problem by only looking at *static* allocas here. That would
1985     // cover the majority of allocas while significantly reducing the likelihood
1986     // of having an @llvm.stackrestore pop up in the middle. However, it's not
1987     // actually impossible for an @llvm.stackrestore to pop up in the middle of
1988     // an entry block. Also, if we have a block that's not attached to a
1989     // function, we can't tell if it's "static" under the current definition.
1990     // Theoretically, this problem could be fixed by creating a new kind of
1991     // instruction kind specifically for static allocas. Such a new instruction
1992     // could be required to be at the top of the entry block, thus preventing it
1993     // from being subject to a @llvm.stackrestore. Instcombine could even
1994     // convert regular allocas into these special allocas. It'd be nifty.
1995     // However, until then, this problem remains open.
1996     //
1997     // So, we'll assume that two non-empty allocas have different addresses
1998     // for now.
1999     //
2000     // With all that, if the offsets are within the bounds of their allocations
2001     // (and not one-past-the-end! so we can't use inbounds!), and their
2002     // allocations aren't the same, the pointers are not equal.
2003     //
2004     // Note that it's not necessary to check for LHS being a global variable
2005     // address, due to canonicalization and constant folding.
2006     if (isa<AllocaInst>(LHS) &&
2007         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2008       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2009       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2010       uint64_t LHSSize, RHSSize;
2011       if (LHSOffsetCI && RHSOffsetCI &&
2012           getObjectSize(LHS, LHSSize, DL, TLI) &&
2013           getObjectSize(RHS, RHSSize, DL, TLI)) {
2014         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2015         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2016         if (!LHSOffsetValue.isNegative() &&
2017             !RHSOffsetValue.isNegative() &&
2018             LHSOffsetValue.ult(LHSSize) &&
2019             RHSOffsetValue.ult(RHSSize)) {
2020           return ConstantInt::get(GetCompareTy(LHS),
2021                                   !CmpInst::isTrueWhenEqual(Pred));
2022         }
2023       }
2024 
2025       // Repeat the above check but this time without depending on DataLayout
2026       // or being able to compute a precise size.
2027       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2028           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2029           LHSOffset->isNullValue() &&
2030           RHSOffset->isNullValue())
2031         return ConstantInt::get(GetCompareTy(LHS),
2032                                 !CmpInst::isTrueWhenEqual(Pred));
2033     }
2034 
2035     // Even if an non-inbounds GEP occurs along the path we can still optimize
2036     // equality comparisons concerning the result. We avoid walking the whole
2037     // chain again by starting where the last calls to
2038     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2039     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2040     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2041     if (LHS == RHS)
2042       return ConstantExpr::getICmp(Pred,
2043                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2044                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2045 
2046     // If one side of the equality comparison must come from a noalias call
2047     // (meaning a system memory allocation function), and the other side must
2048     // come from a pointer that cannot overlap with dynamically-allocated
2049     // memory within the lifetime of the current function (allocas, byval
2050     // arguments, globals), then determine the comparison result here.
2051     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2052     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2053     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2054 
2055     // Is the set of underlying objects all noalias calls?
2056     auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
2057       return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
2058     };
2059 
2060     // Is the set of underlying objects all things which must be disjoint from
2061     // noalias calls. For allocas, we consider only static ones (dynamic
2062     // allocas might be transformed into calls to malloc not simultaneously
2063     // live with the compared-to allocation). For globals, we exclude symbols
2064     // that might be resolve lazily to symbols in another dynamically-loaded
2065     // library (and, thus, could be malloc'ed by the implementation).
2066     auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
2067       return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2068         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2069           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2070         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2071           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2072                   GV->hasProtectedVisibility() || GV->hasUnnamedAddr()) &&
2073                  !GV->isThreadLocal();
2074         if (const Argument *A = dyn_cast<Argument>(V))
2075           return A->hasByValAttr();
2076         return false;
2077       });
2078     };
2079 
2080     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2081         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2082         return ConstantInt::get(GetCompareTy(LHS),
2083                                 !CmpInst::isTrueWhenEqual(Pred));
2084   }
2085 
2086   // Otherwise, fail.
2087   return nullptr;
2088 }
2089 
2090 /// Given operands for an ICmpInst, see if we can fold the result.
2091 /// If not, this returns null.
2092 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2093                                const Query &Q, unsigned MaxRecurse) {
2094   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2095   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2096 
2097   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2098     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2099       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2100 
2101     // If we have a constant, make sure it is on the RHS.
2102     std::swap(LHS, RHS);
2103     Pred = CmpInst::getSwappedPredicate(Pred);
2104   }
2105 
2106   Type *ITy = GetCompareTy(LHS); // The return type.
2107   Type *OpTy = LHS->getType();   // The operand type.
2108 
2109   // icmp X, X -> true/false
2110   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2111   // because X could be 0.
2112   if (LHS == RHS || isa<UndefValue>(RHS))
2113     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2114 
2115   // Special case logic when the operands have i1 type.
2116   if (OpTy->getScalarType()->isIntegerTy(1)) {
2117     switch (Pred) {
2118     default: break;
2119     case ICmpInst::ICMP_EQ:
2120       // X == 1 -> X
2121       if (match(RHS, m_One()))
2122         return LHS;
2123       break;
2124     case ICmpInst::ICMP_NE:
2125       // X != 0 -> X
2126       if (match(RHS, m_Zero()))
2127         return LHS;
2128       break;
2129     case ICmpInst::ICMP_UGT:
2130       // X >u 0 -> X
2131       if (match(RHS, m_Zero()))
2132         return LHS;
2133       break;
2134     case ICmpInst::ICMP_UGE: {
2135       // X >=u 1 -> X
2136       if (match(RHS, m_One()))
2137         return LHS;
2138       bool ImpliedTrue;
2139       if (isImpliedCondition(RHS, LHS, ImpliedTrue, Q.DL) && ImpliedTrue)
2140         return getTrue(ITy);
2141       break;
2142     }
2143     case ICmpInst::ICMP_SGE: {
2144       /// For signed comparison, the values for an i1 are 0 and -1
2145       /// respectively. This maps into a truth table of:
2146       /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2147       ///  0  |  0  |  1 (0 >= 0)   |  1
2148       ///  0  |  1  |  1 (0 >= -1)  |  1
2149       ///  1  |  0  |  0 (-1 >= 0)  |  0
2150       ///  1  |  1  |  1 (-1 >= -1) |  1
2151       bool ImpliedTrue;
2152       if (isImpliedCondition(LHS, RHS, ImpliedTrue, Q.DL) && ImpliedTrue)
2153         return getTrue(ITy);
2154       break;
2155     }
2156     case ICmpInst::ICMP_SLT:
2157       // X <s 0 -> X
2158       if (match(RHS, m_Zero()))
2159         return LHS;
2160       break;
2161     case ICmpInst::ICMP_SLE:
2162       // X <=s -1 -> X
2163       if (match(RHS, m_One()))
2164         return LHS;
2165       break;
2166     case ICmpInst::ICMP_ULE: {
2167       bool ImpliedTrue;
2168       if (isImpliedCondition(LHS, RHS, ImpliedTrue, Q.DL) && ImpliedTrue)
2169         return getTrue(ITy);
2170       break;
2171     }
2172     }
2173   }
2174 
2175   // If we are comparing with zero then try hard since this is a common case.
2176   if (match(RHS, m_Zero())) {
2177     bool LHSKnownNonNegative, LHSKnownNegative;
2178     switch (Pred) {
2179     default: llvm_unreachable("Unknown ICmp predicate!");
2180     case ICmpInst::ICMP_ULT:
2181       return getFalse(ITy);
2182     case ICmpInst::ICMP_UGE:
2183       return getTrue(ITy);
2184     case ICmpInst::ICMP_EQ:
2185     case ICmpInst::ICMP_ULE:
2186       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2187         return getFalse(ITy);
2188       break;
2189     case ICmpInst::ICMP_NE:
2190     case ICmpInst::ICMP_UGT:
2191       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2192         return getTrue(ITy);
2193       break;
2194     case ICmpInst::ICMP_SLT:
2195       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2196                      Q.CxtI, Q.DT);
2197       if (LHSKnownNegative)
2198         return getTrue(ITy);
2199       if (LHSKnownNonNegative)
2200         return getFalse(ITy);
2201       break;
2202     case ICmpInst::ICMP_SLE:
2203       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2204                      Q.CxtI, Q.DT);
2205       if (LHSKnownNegative)
2206         return getTrue(ITy);
2207       if (LHSKnownNonNegative &&
2208           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2209         return getFalse(ITy);
2210       break;
2211     case ICmpInst::ICMP_SGE:
2212       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2213                      Q.CxtI, Q.DT);
2214       if (LHSKnownNegative)
2215         return getFalse(ITy);
2216       if (LHSKnownNonNegative)
2217         return getTrue(ITy);
2218       break;
2219     case ICmpInst::ICMP_SGT:
2220       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2221                      Q.CxtI, Q.DT);
2222       if (LHSKnownNegative)
2223         return getFalse(ITy);
2224       if (LHSKnownNonNegative &&
2225           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2226         return getTrue(ITy);
2227       break;
2228     }
2229   }
2230 
2231   // See if we are doing a comparison with a constant integer.
2232   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2233     // Rule out tautological comparisons (eg., ult 0 or uge 0).
2234     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2235     if (RHS_CR.isEmptySet())
2236       return ConstantInt::getFalse(CI->getContext());
2237     if (RHS_CR.isFullSet())
2238       return ConstantInt::getTrue(CI->getContext());
2239 
2240     // Many binary operators with constant RHS have easy to compute constant
2241     // range.  Use them to check whether the comparison is a tautology.
2242     unsigned Width = CI->getBitWidth();
2243     APInt Lower = APInt(Width, 0);
2244     APInt Upper = APInt(Width, 0);
2245     ConstantInt *CI2;
2246     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2247       // 'urem x, CI2' produces [0, CI2).
2248       Upper = CI2->getValue();
2249     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2250       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2251       Upper = CI2->getValue().abs();
2252       Lower = (-Upper) + 1;
2253     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2254       // 'udiv CI2, x' produces [0, CI2].
2255       Upper = CI2->getValue() + 1;
2256     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2257       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2258       APInt NegOne = APInt::getAllOnesValue(Width);
2259       if (!CI2->isZero())
2260         Upper = NegOne.udiv(CI2->getValue()) + 1;
2261     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2262       if (CI2->isMinSignedValue()) {
2263         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2264         Lower = CI2->getValue();
2265         Upper = Lower.lshr(1) + 1;
2266       } else {
2267         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2268         Upper = CI2->getValue().abs() + 1;
2269         Lower = (-Upper) + 1;
2270       }
2271     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2272       APInt IntMin = APInt::getSignedMinValue(Width);
2273       APInt IntMax = APInt::getSignedMaxValue(Width);
2274       APInt Val = CI2->getValue();
2275       if (Val.isAllOnesValue()) {
2276         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2277         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2278         Lower = IntMin + 1;
2279         Upper = IntMax + 1;
2280       } else if (Val.countLeadingZeros() < Width - 1) {
2281         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2282         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2283         Lower = IntMin.sdiv(Val);
2284         Upper = IntMax.sdiv(Val);
2285         if (Lower.sgt(Upper))
2286           std::swap(Lower, Upper);
2287         Upper = Upper + 1;
2288         assert(Upper != Lower && "Upper part of range has wrapped!");
2289       }
2290     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2291       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2292       Lower = CI2->getValue();
2293       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2294     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2295       if (CI2->isNegative()) {
2296         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2297         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2298         Lower = CI2->getValue().shl(ShiftAmount);
2299         Upper = CI2->getValue() + 1;
2300       } else {
2301         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2302         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2303         Lower = CI2->getValue();
2304         Upper = CI2->getValue().shl(ShiftAmount) + 1;
2305       }
2306     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2307       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2308       APInt NegOne = APInt::getAllOnesValue(Width);
2309       if (CI2->getValue().ult(Width))
2310         Upper = NegOne.lshr(CI2->getValue()) + 1;
2311     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2312       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2313       unsigned ShiftAmount = Width - 1;
2314       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2315         ShiftAmount = CI2->getValue().countTrailingZeros();
2316       Lower = CI2->getValue().lshr(ShiftAmount);
2317       Upper = CI2->getValue() + 1;
2318     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2319       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2320       APInt IntMin = APInt::getSignedMinValue(Width);
2321       APInt IntMax = APInt::getSignedMaxValue(Width);
2322       if (CI2->getValue().ult(Width)) {
2323         Lower = IntMin.ashr(CI2->getValue());
2324         Upper = IntMax.ashr(CI2->getValue()) + 1;
2325       }
2326     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2327       unsigned ShiftAmount = Width - 1;
2328       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2329         ShiftAmount = CI2->getValue().countTrailingZeros();
2330       if (CI2->isNegative()) {
2331         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2332         Lower = CI2->getValue();
2333         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2334       } else {
2335         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2336         Lower = CI2->getValue().ashr(ShiftAmount);
2337         Upper = CI2->getValue() + 1;
2338       }
2339     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2340       // 'or x, CI2' produces [CI2, UINT_MAX].
2341       Lower = CI2->getValue();
2342     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2343       // 'and x, CI2' produces [0, CI2].
2344       Upper = CI2->getValue() + 1;
2345     } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2346       // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2347       Lower = CI2->getValue();
2348     }
2349 
2350     ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2351                                           : ConstantRange(Width, true);
2352 
2353     if (auto *I = dyn_cast<Instruction>(LHS))
2354       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2355         LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2356 
2357     if (!LHS_CR.isFullSet()) {
2358       if (RHS_CR.contains(LHS_CR))
2359         return ConstantInt::getTrue(RHS->getContext());
2360       if (RHS_CR.inverse().contains(LHS_CR))
2361         return ConstantInt::getFalse(RHS->getContext());
2362     }
2363   }
2364 
2365   // If both operands have range metadata, use the metadata
2366   // to simplify the comparison.
2367   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2368     auto RHS_Instr = dyn_cast<Instruction>(RHS);
2369     auto LHS_Instr = dyn_cast<Instruction>(LHS);
2370 
2371     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2372         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2373       auto RHS_CR = getConstantRangeFromMetadata(
2374           *RHS_Instr->getMetadata(LLVMContext::MD_range));
2375       auto LHS_CR = getConstantRangeFromMetadata(
2376           *LHS_Instr->getMetadata(LLVMContext::MD_range));
2377 
2378       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2379       if (Satisfied_CR.contains(LHS_CR))
2380         return ConstantInt::getTrue(RHS->getContext());
2381 
2382       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2383                 CmpInst::getInversePredicate(Pred), RHS_CR);
2384       if (InversedSatisfied_CR.contains(LHS_CR))
2385         return ConstantInt::getFalse(RHS->getContext());
2386     }
2387   }
2388 
2389   // Compare of cast, for example (zext X) != 0 -> X != 0
2390   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2391     Instruction *LI = cast<CastInst>(LHS);
2392     Value *SrcOp = LI->getOperand(0);
2393     Type *SrcTy = SrcOp->getType();
2394     Type *DstTy = LI->getType();
2395 
2396     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2397     // if the integer type is the same size as the pointer type.
2398     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2399         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2400       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2401         // Transfer the cast to the constant.
2402         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2403                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2404                                         Q, MaxRecurse-1))
2405           return V;
2406       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2407         if (RI->getOperand(0)->getType() == SrcTy)
2408           // Compare without the cast.
2409           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2410                                           Q, MaxRecurse-1))
2411             return V;
2412       }
2413     }
2414 
2415     if (isa<ZExtInst>(LHS)) {
2416       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2417       // same type.
2418       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2419         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2420           // Compare X and Y.  Note that signed predicates become unsigned.
2421           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2422                                           SrcOp, RI->getOperand(0), Q,
2423                                           MaxRecurse-1))
2424             return V;
2425       }
2426       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2427       // too.  If not, then try to deduce the result of the comparison.
2428       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2429         // Compute the constant that would happen if we truncated to SrcTy then
2430         // reextended to DstTy.
2431         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2432         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2433 
2434         // If the re-extended constant didn't change then this is effectively
2435         // also a case of comparing two zero-extended values.
2436         if (RExt == CI && MaxRecurse)
2437           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2438                                         SrcOp, Trunc, Q, MaxRecurse-1))
2439             return V;
2440 
2441         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2442         // there.  Use this to work out the result of the comparison.
2443         if (RExt != CI) {
2444           switch (Pred) {
2445           default: llvm_unreachable("Unknown ICmp predicate!");
2446           // LHS <u RHS.
2447           case ICmpInst::ICMP_EQ:
2448           case ICmpInst::ICMP_UGT:
2449           case ICmpInst::ICMP_UGE:
2450             return ConstantInt::getFalse(CI->getContext());
2451 
2452           case ICmpInst::ICMP_NE:
2453           case ICmpInst::ICMP_ULT:
2454           case ICmpInst::ICMP_ULE:
2455             return ConstantInt::getTrue(CI->getContext());
2456 
2457           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2458           // is non-negative then LHS <s RHS.
2459           case ICmpInst::ICMP_SGT:
2460           case ICmpInst::ICMP_SGE:
2461             return CI->getValue().isNegative() ?
2462               ConstantInt::getTrue(CI->getContext()) :
2463               ConstantInt::getFalse(CI->getContext());
2464 
2465           case ICmpInst::ICMP_SLT:
2466           case ICmpInst::ICMP_SLE:
2467             return CI->getValue().isNegative() ?
2468               ConstantInt::getFalse(CI->getContext()) :
2469               ConstantInt::getTrue(CI->getContext());
2470           }
2471         }
2472       }
2473     }
2474 
2475     if (isa<SExtInst>(LHS)) {
2476       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2477       // same type.
2478       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2479         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2480           // Compare X and Y.  Note that the predicate does not change.
2481           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2482                                           Q, MaxRecurse-1))
2483             return V;
2484       }
2485       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2486       // too.  If not, then try to deduce the result of the comparison.
2487       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2488         // Compute the constant that would happen if we truncated to SrcTy then
2489         // reextended to DstTy.
2490         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2491         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2492 
2493         // If the re-extended constant didn't change then this is effectively
2494         // also a case of comparing two sign-extended values.
2495         if (RExt == CI && MaxRecurse)
2496           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2497             return V;
2498 
2499         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2500         // bits there.  Use this to work out the result of the comparison.
2501         if (RExt != CI) {
2502           switch (Pred) {
2503           default: llvm_unreachable("Unknown ICmp predicate!");
2504           case ICmpInst::ICMP_EQ:
2505             return ConstantInt::getFalse(CI->getContext());
2506           case ICmpInst::ICMP_NE:
2507             return ConstantInt::getTrue(CI->getContext());
2508 
2509           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2510           // LHS >s RHS.
2511           case ICmpInst::ICMP_SGT:
2512           case ICmpInst::ICMP_SGE:
2513             return CI->getValue().isNegative() ?
2514               ConstantInt::getTrue(CI->getContext()) :
2515               ConstantInt::getFalse(CI->getContext());
2516           case ICmpInst::ICMP_SLT:
2517           case ICmpInst::ICMP_SLE:
2518             return CI->getValue().isNegative() ?
2519               ConstantInt::getFalse(CI->getContext()) :
2520               ConstantInt::getTrue(CI->getContext());
2521 
2522           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2523           // LHS >u RHS.
2524           case ICmpInst::ICMP_UGT:
2525           case ICmpInst::ICMP_UGE:
2526             // Comparison is true iff the LHS <s 0.
2527             if (MaxRecurse)
2528               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2529                                               Constant::getNullValue(SrcTy),
2530                                               Q, MaxRecurse-1))
2531                 return V;
2532             break;
2533           case ICmpInst::ICMP_ULT:
2534           case ICmpInst::ICMP_ULE:
2535             // Comparison is true iff the LHS >=s 0.
2536             if (MaxRecurse)
2537               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2538                                               Constant::getNullValue(SrcTy),
2539                                               Q, MaxRecurse-1))
2540                 return V;
2541             break;
2542           }
2543         }
2544       }
2545     }
2546   }
2547 
2548   // icmp eq|ne X, Y -> false|true if X != Y
2549   if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2550       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2551     LLVMContext &Ctx = LHS->getType()->getContext();
2552     return Pred == ICmpInst::ICMP_NE ?
2553       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2554   }
2555 
2556   // Special logic for binary operators.
2557   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2558   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2559   if (MaxRecurse && (LBO || RBO)) {
2560     // Analyze the case when either LHS or RHS is an add instruction.
2561     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2562     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2563     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2564     if (LBO && LBO->getOpcode() == Instruction::Add) {
2565       A = LBO->getOperand(0); B = LBO->getOperand(1);
2566       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2567         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2568         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2569     }
2570     if (RBO && RBO->getOpcode() == Instruction::Add) {
2571       C = RBO->getOperand(0); D = RBO->getOperand(1);
2572       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2573         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2574         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2575     }
2576 
2577     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2578     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2579       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2580                                       Constant::getNullValue(RHS->getType()),
2581                                       Q, MaxRecurse-1))
2582         return V;
2583 
2584     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2585     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2586       if (Value *V = SimplifyICmpInst(Pred,
2587                                       Constant::getNullValue(LHS->getType()),
2588                                       C == LHS ? D : C, Q, MaxRecurse-1))
2589         return V;
2590 
2591     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2592     if (A && C && (A == C || A == D || B == C || B == D) &&
2593         NoLHSWrapProblem && NoRHSWrapProblem) {
2594       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2595       Value *Y, *Z;
2596       if (A == C) {
2597         // C + B == C + D  ->  B == D
2598         Y = B;
2599         Z = D;
2600       } else if (A == D) {
2601         // D + B == C + D  ->  B == C
2602         Y = B;
2603         Z = C;
2604       } else if (B == C) {
2605         // A + C == C + D  ->  A == D
2606         Y = A;
2607         Z = D;
2608       } else {
2609         assert(B == D);
2610         // A + D == C + D  ->  A == C
2611         Y = A;
2612         Z = C;
2613       }
2614       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2615         return V;
2616     }
2617   }
2618 
2619   // icmp pred (or X, Y), X
2620   if (LBO && match(LBO, m_CombineOr(m_Or(m_Value(), m_Specific(RHS)),
2621                                     m_Or(m_Specific(RHS), m_Value())))) {
2622     if (Pred == ICmpInst::ICMP_ULT)
2623       return getFalse(ITy);
2624     if (Pred == ICmpInst::ICMP_UGE)
2625       return getTrue(ITy);
2626   }
2627   // icmp pred X, (or X, Y)
2628   if (RBO && match(RBO, m_CombineOr(m_Or(m_Value(), m_Specific(LHS)),
2629                                     m_Or(m_Specific(LHS), m_Value())))) {
2630     if (Pred == ICmpInst::ICMP_ULE)
2631       return getTrue(ITy);
2632     if (Pred == ICmpInst::ICMP_UGT)
2633       return getFalse(ITy);
2634   }
2635 
2636   // icmp pred (and X, Y), X
2637   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2638                                     m_And(m_Specific(RHS), m_Value())))) {
2639     if (Pred == ICmpInst::ICMP_UGT)
2640       return getFalse(ITy);
2641     if (Pred == ICmpInst::ICMP_ULE)
2642       return getTrue(ITy);
2643   }
2644   // icmp pred X, (and X, Y)
2645   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2646                                     m_And(m_Specific(LHS), m_Value())))) {
2647     if (Pred == ICmpInst::ICMP_UGE)
2648       return getTrue(ITy);
2649     if (Pred == ICmpInst::ICMP_ULT)
2650       return getFalse(ITy);
2651   }
2652 
2653   // 0 - (zext X) pred C
2654   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2655     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2656       if (RHSC->getValue().isStrictlyPositive()) {
2657         if (Pred == ICmpInst::ICMP_SLT)
2658           return ConstantInt::getTrue(RHSC->getContext());
2659         if (Pred == ICmpInst::ICMP_SGE)
2660           return ConstantInt::getFalse(RHSC->getContext());
2661         if (Pred == ICmpInst::ICMP_EQ)
2662           return ConstantInt::getFalse(RHSC->getContext());
2663         if (Pred == ICmpInst::ICMP_NE)
2664           return ConstantInt::getTrue(RHSC->getContext());
2665       }
2666       if (RHSC->getValue().isNonNegative()) {
2667         if (Pred == ICmpInst::ICMP_SLE)
2668           return ConstantInt::getTrue(RHSC->getContext());
2669         if (Pred == ICmpInst::ICMP_SGT)
2670           return ConstantInt::getFalse(RHSC->getContext());
2671       }
2672     }
2673   }
2674 
2675   // icmp pred (urem X, Y), Y
2676   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2677     bool KnownNonNegative, KnownNegative;
2678     switch (Pred) {
2679     default:
2680       break;
2681     case ICmpInst::ICMP_SGT:
2682     case ICmpInst::ICMP_SGE:
2683       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2684                      Q.CxtI, Q.DT);
2685       if (!KnownNonNegative)
2686         break;
2687       // fall-through
2688     case ICmpInst::ICMP_EQ:
2689     case ICmpInst::ICMP_UGT:
2690     case ICmpInst::ICMP_UGE:
2691       return getFalse(ITy);
2692     case ICmpInst::ICMP_SLT:
2693     case ICmpInst::ICMP_SLE:
2694       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2695                      Q.CxtI, Q.DT);
2696       if (!KnownNonNegative)
2697         break;
2698       // fall-through
2699     case ICmpInst::ICMP_NE:
2700     case ICmpInst::ICMP_ULT:
2701     case ICmpInst::ICMP_ULE:
2702       return getTrue(ITy);
2703     }
2704   }
2705 
2706   // icmp pred X, (urem Y, X)
2707   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2708     bool KnownNonNegative, KnownNegative;
2709     switch (Pred) {
2710     default:
2711       break;
2712     case ICmpInst::ICMP_SGT:
2713     case ICmpInst::ICMP_SGE:
2714       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2715                      Q.CxtI, Q.DT);
2716       if (!KnownNonNegative)
2717         break;
2718       // fall-through
2719     case ICmpInst::ICMP_NE:
2720     case ICmpInst::ICMP_UGT:
2721     case ICmpInst::ICMP_UGE:
2722       return getTrue(ITy);
2723     case ICmpInst::ICMP_SLT:
2724     case ICmpInst::ICMP_SLE:
2725       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2726                      Q.CxtI, Q.DT);
2727       if (!KnownNonNegative)
2728         break;
2729       // fall-through
2730     case ICmpInst::ICMP_EQ:
2731     case ICmpInst::ICMP_ULT:
2732     case ICmpInst::ICMP_ULE:
2733       return getFalse(ITy);
2734     }
2735   }
2736 
2737   // x >> y <=u x
2738   // x udiv y <=u x.
2739   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2740               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2741     // icmp pred (X op Y), X
2742     if (Pred == ICmpInst::ICMP_UGT)
2743       return getFalse(ITy);
2744     if (Pred == ICmpInst::ICMP_ULE)
2745       return getTrue(ITy);
2746   }
2747 
2748   // handle:
2749   //   CI2 << X == CI
2750   //   CI2 << X != CI
2751   //
2752   //   where CI2 is a power of 2 and CI isn't
2753   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2754     const APInt *CI2Val, *CIVal = &CI->getValue();
2755     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2756         CI2Val->isPowerOf2()) {
2757       if (!CIVal->isPowerOf2()) {
2758         // CI2 << X can equal zero in some circumstances,
2759         // this simplification is unsafe if CI is zero.
2760         //
2761         // We know it is safe if:
2762         // - The shift is nsw, we can't shift out the one bit.
2763         // - The shift is nuw, we can't shift out the one bit.
2764         // - CI2 is one
2765         // - CI isn't zero
2766         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2767             *CI2Val == 1 || !CI->isZero()) {
2768           if (Pred == ICmpInst::ICMP_EQ)
2769             return ConstantInt::getFalse(RHS->getContext());
2770           if (Pred == ICmpInst::ICMP_NE)
2771             return ConstantInt::getTrue(RHS->getContext());
2772         }
2773       }
2774       if (CIVal->isSignBit() && *CI2Val == 1) {
2775         if (Pred == ICmpInst::ICMP_UGT)
2776           return ConstantInt::getFalse(RHS->getContext());
2777         if (Pred == ICmpInst::ICMP_ULE)
2778           return ConstantInt::getTrue(RHS->getContext());
2779       }
2780     }
2781   }
2782 
2783   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2784       LBO->getOperand(1) == RBO->getOperand(1)) {
2785     switch (LBO->getOpcode()) {
2786     default: break;
2787     case Instruction::UDiv:
2788     case Instruction::LShr:
2789       if (ICmpInst::isSigned(Pred))
2790         break;
2791       // fall-through
2792     case Instruction::SDiv:
2793     case Instruction::AShr:
2794       if (!LBO->isExact() || !RBO->isExact())
2795         break;
2796       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2797                                       RBO->getOperand(0), Q, MaxRecurse-1))
2798         return V;
2799       break;
2800     case Instruction::Shl: {
2801       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2802       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2803       if (!NUW && !NSW)
2804         break;
2805       if (!NSW && ICmpInst::isSigned(Pred))
2806         break;
2807       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2808                                       RBO->getOperand(0), Q, MaxRecurse-1))
2809         return V;
2810       break;
2811     }
2812     }
2813   }
2814 
2815   // Simplify comparisons involving max/min.
2816   Value *A, *B;
2817   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2818   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2819 
2820   // Signed variants on "max(a,b)>=a -> true".
2821   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2822     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2823     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2824     // We analyze this as smax(A, B) pred A.
2825     P = Pred;
2826   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2827              (A == LHS || B == LHS)) {
2828     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2829     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2830     // We analyze this as smax(A, B) swapped-pred A.
2831     P = CmpInst::getSwappedPredicate(Pred);
2832   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2833              (A == RHS || B == RHS)) {
2834     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2835     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2836     // We analyze this as smax(-A, -B) swapped-pred -A.
2837     // Note that we do not need to actually form -A or -B thanks to EqP.
2838     P = CmpInst::getSwappedPredicate(Pred);
2839   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2840              (A == LHS || B == LHS)) {
2841     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2842     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2843     // We analyze this as smax(-A, -B) pred -A.
2844     // Note that we do not need to actually form -A or -B thanks to EqP.
2845     P = Pred;
2846   }
2847   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2848     // Cases correspond to "max(A, B) p A".
2849     switch (P) {
2850     default:
2851       break;
2852     case CmpInst::ICMP_EQ:
2853     case CmpInst::ICMP_SLE:
2854       // Equivalent to "A EqP B".  This may be the same as the condition tested
2855       // in the max/min; if so, we can just return that.
2856       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2857         return V;
2858       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2859         return V;
2860       // Otherwise, see if "A EqP B" simplifies.
2861       if (MaxRecurse)
2862         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2863           return V;
2864       break;
2865     case CmpInst::ICMP_NE:
2866     case CmpInst::ICMP_SGT: {
2867       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2868       // Equivalent to "A InvEqP B".  This may be the same as the condition
2869       // tested in the max/min; if so, we can just return that.
2870       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2871         return V;
2872       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2873         return V;
2874       // Otherwise, see if "A InvEqP B" simplifies.
2875       if (MaxRecurse)
2876         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2877           return V;
2878       break;
2879     }
2880     case CmpInst::ICMP_SGE:
2881       // Always true.
2882       return getTrue(ITy);
2883     case CmpInst::ICMP_SLT:
2884       // Always false.
2885       return getFalse(ITy);
2886     }
2887   }
2888 
2889   // Unsigned variants on "max(a,b)>=a -> true".
2890   P = CmpInst::BAD_ICMP_PREDICATE;
2891   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2892     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2893     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2894     // We analyze this as umax(A, B) pred A.
2895     P = Pred;
2896   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2897              (A == LHS || B == LHS)) {
2898     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2899     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2900     // We analyze this as umax(A, B) swapped-pred A.
2901     P = CmpInst::getSwappedPredicate(Pred);
2902   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2903              (A == RHS || B == RHS)) {
2904     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2905     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2906     // We analyze this as umax(-A, -B) swapped-pred -A.
2907     // Note that we do not need to actually form -A or -B thanks to EqP.
2908     P = CmpInst::getSwappedPredicate(Pred);
2909   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2910              (A == LHS || B == LHS)) {
2911     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2912     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2913     // We analyze this as umax(-A, -B) pred -A.
2914     // Note that we do not need to actually form -A or -B thanks to EqP.
2915     P = Pred;
2916   }
2917   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2918     // Cases correspond to "max(A, B) p A".
2919     switch (P) {
2920     default:
2921       break;
2922     case CmpInst::ICMP_EQ:
2923     case CmpInst::ICMP_ULE:
2924       // Equivalent to "A EqP B".  This may be the same as the condition tested
2925       // in the max/min; if so, we can just return that.
2926       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2927         return V;
2928       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2929         return V;
2930       // Otherwise, see if "A EqP B" simplifies.
2931       if (MaxRecurse)
2932         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2933           return V;
2934       break;
2935     case CmpInst::ICMP_NE:
2936     case CmpInst::ICMP_UGT: {
2937       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2938       // Equivalent to "A InvEqP B".  This may be the same as the condition
2939       // tested in the max/min; if so, we can just return that.
2940       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2941         return V;
2942       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2943         return V;
2944       // Otherwise, see if "A InvEqP B" simplifies.
2945       if (MaxRecurse)
2946         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2947           return V;
2948       break;
2949     }
2950     case CmpInst::ICMP_UGE:
2951       // Always true.
2952       return getTrue(ITy);
2953     case CmpInst::ICMP_ULT:
2954       // Always false.
2955       return getFalse(ITy);
2956     }
2957   }
2958 
2959   // Variants on "max(x,y) >= min(x,z)".
2960   Value *C, *D;
2961   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2962       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2963       (A == C || A == D || B == C || B == D)) {
2964     // max(x, ?) pred min(x, ?).
2965     if (Pred == CmpInst::ICMP_SGE)
2966       // Always true.
2967       return getTrue(ITy);
2968     if (Pred == CmpInst::ICMP_SLT)
2969       // Always false.
2970       return getFalse(ITy);
2971   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2972              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2973              (A == C || A == D || B == C || B == D)) {
2974     // min(x, ?) pred max(x, ?).
2975     if (Pred == CmpInst::ICMP_SLE)
2976       // Always true.
2977       return getTrue(ITy);
2978     if (Pred == CmpInst::ICMP_SGT)
2979       // Always false.
2980       return getFalse(ITy);
2981   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2982              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2983              (A == C || A == D || B == C || B == D)) {
2984     // max(x, ?) pred min(x, ?).
2985     if (Pred == CmpInst::ICMP_UGE)
2986       // Always true.
2987       return getTrue(ITy);
2988     if (Pred == CmpInst::ICMP_ULT)
2989       // Always false.
2990       return getFalse(ITy);
2991   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2992              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2993              (A == C || A == D || B == C || B == D)) {
2994     // min(x, ?) pred max(x, ?).
2995     if (Pred == CmpInst::ICMP_ULE)
2996       // Always true.
2997       return getTrue(ITy);
2998     if (Pred == CmpInst::ICMP_UGT)
2999       // Always false.
3000       return getFalse(ITy);
3001   }
3002 
3003   // Simplify comparisons of related pointers using a powerful, recursive
3004   // GEP-walk when we have target data available..
3005   if (LHS->getType()->isPointerTy())
3006     if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
3007       return C;
3008 
3009   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3010     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3011       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3012           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3013           (ICmpInst::isEquality(Pred) ||
3014            (GLHS->isInBounds() && GRHS->isInBounds() &&
3015             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3016         // The bases are equal and the indices are constant.  Build a constant
3017         // expression GEP with the same indices and a null base pointer to see
3018         // what constant folding can make out of it.
3019         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3020         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3021         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3022             GLHS->getSourceElementType(), Null, IndicesLHS);
3023 
3024         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3025         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3026             GLHS->getSourceElementType(), Null, IndicesRHS);
3027         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3028       }
3029     }
3030   }
3031 
3032   // If a bit is known to be zero for A and known to be one for B,
3033   // then A and B cannot be equal.
3034   if (ICmpInst::isEquality(Pred)) {
3035     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3036       uint32_t BitWidth = CI->getBitWidth();
3037       APInt LHSKnownZero(BitWidth, 0);
3038       APInt LHSKnownOne(BitWidth, 0);
3039       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3040                        Q.CxtI, Q.DT);
3041       const APInt &RHSVal = CI->getValue();
3042       if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3043         return Pred == ICmpInst::ICMP_EQ
3044                    ? ConstantInt::getFalse(CI->getContext())
3045                    : ConstantInt::getTrue(CI->getContext());
3046     }
3047   }
3048 
3049   // If the comparison is with the result of a select instruction, check whether
3050   // comparing with either branch of the select always yields the same value.
3051   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3052     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3053       return V;
3054 
3055   // If the comparison is with the result of a phi instruction, check whether
3056   // doing the compare with each incoming phi value yields a common result.
3057   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3058     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3059       return V;
3060 
3061   return nullptr;
3062 }
3063 
3064 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3065                               const DataLayout &DL,
3066                               const TargetLibraryInfo *TLI,
3067                               const DominatorTree *DT, AssumptionCache *AC,
3068                               const Instruction *CxtI) {
3069   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3070                             RecursionLimit);
3071 }
3072 
3073 /// Given operands for an FCmpInst, see if we can fold the result.
3074 /// If not, this returns null.
3075 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3076                                FastMathFlags FMF, const Query &Q,
3077                                unsigned MaxRecurse) {
3078   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3079   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3080 
3081   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3082     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3083       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3084 
3085     // If we have a constant, make sure it is on the RHS.
3086     std::swap(LHS, RHS);
3087     Pred = CmpInst::getSwappedPredicate(Pred);
3088   }
3089 
3090   // Fold trivial predicates.
3091   if (Pred == FCmpInst::FCMP_FALSE)
3092     return ConstantInt::get(GetCompareTy(LHS), 0);
3093   if (Pred == FCmpInst::FCMP_TRUE)
3094     return ConstantInt::get(GetCompareTy(LHS), 1);
3095 
3096   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3097   if (FMF.noNaNs()) {
3098     if (Pred == FCmpInst::FCMP_UNO)
3099       return ConstantInt::get(GetCompareTy(LHS), 0);
3100     if (Pred == FCmpInst::FCMP_ORD)
3101       return ConstantInt::get(GetCompareTy(LHS), 1);
3102   }
3103 
3104   // fcmp pred x, undef  and  fcmp pred undef, x
3105   // fold to true if unordered, false if ordered
3106   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3107     // Choosing NaN for the undef will always make unordered comparison succeed
3108     // and ordered comparison fail.
3109     return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3110   }
3111 
3112   // fcmp x,x -> true/false.  Not all compares are foldable.
3113   if (LHS == RHS) {
3114     if (CmpInst::isTrueWhenEqual(Pred))
3115       return ConstantInt::get(GetCompareTy(LHS), 1);
3116     if (CmpInst::isFalseWhenEqual(Pred))
3117       return ConstantInt::get(GetCompareTy(LHS), 0);
3118   }
3119 
3120   // Handle fcmp with constant RHS
3121   const ConstantFP *CFP = nullptr;
3122   if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3123     if (RHS->getType()->isVectorTy())
3124       CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3125     else
3126       CFP = dyn_cast<ConstantFP>(RHSC);
3127   }
3128   if (CFP) {
3129     // If the constant is a nan, see if we can fold the comparison based on it.
3130     if (CFP->getValueAPF().isNaN()) {
3131       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3132         return ConstantInt::getFalse(CFP->getContext());
3133       assert(FCmpInst::isUnordered(Pred) &&
3134              "Comparison must be either ordered or unordered!");
3135       // True if unordered.
3136       return ConstantInt::get(GetCompareTy(LHS), 1);
3137     }
3138     // Check whether the constant is an infinity.
3139     if (CFP->getValueAPF().isInfinity()) {
3140       if (CFP->getValueAPF().isNegative()) {
3141         switch (Pred) {
3142         case FCmpInst::FCMP_OLT:
3143           // No value is ordered and less than negative infinity.
3144           return ConstantInt::get(GetCompareTy(LHS), 0);
3145         case FCmpInst::FCMP_UGE:
3146           // All values are unordered with or at least negative infinity.
3147           return ConstantInt::get(GetCompareTy(LHS), 1);
3148         default:
3149           break;
3150         }
3151       } else {
3152         switch (Pred) {
3153         case FCmpInst::FCMP_OGT:
3154           // No value is ordered and greater than infinity.
3155           return ConstantInt::get(GetCompareTy(LHS), 0);
3156         case FCmpInst::FCMP_ULE:
3157           // All values are unordered with and at most infinity.
3158           return ConstantInt::get(GetCompareTy(LHS), 1);
3159         default:
3160           break;
3161         }
3162       }
3163     }
3164     if (CFP->getValueAPF().isZero()) {
3165       switch (Pred) {
3166       case FCmpInst::FCMP_UGE:
3167         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3168           return ConstantInt::get(GetCompareTy(LHS), 1);
3169         break;
3170       case FCmpInst::FCMP_OLT:
3171         // X < 0
3172         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3173           return ConstantInt::get(GetCompareTy(LHS), 0);
3174         break;
3175       default:
3176         break;
3177       }
3178     }
3179   }
3180 
3181   // If the comparison is with the result of a select instruction, check whether
3182   // comparing with either branch of the select always yields the same value.
3183   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3184     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3185       return V;
3186 
3187   // If the comparison is with the result of a phi instruction, check whether
3188   // doing the compare with each incoming phi value yields a common result.
3189   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3190     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3191       return V;
3192 
3193   return nullptr;
3194 }
3195 
3196 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3197                               FastMathFlags FMF, const DataLayout &DL,
3198                               const TargetLibraryInfo *TLI,
3199                               const DominatorTree *DT, AssumptionCache *AC,
3200                               const Instruction *CxtI) {
3201   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3202                             Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3203 }
3204 
3205 /// See if V simplifies when its operand Op is replaced with RepOp.
3206 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3207                                            const Query &Q,
3208                                            unsigned MaxRecurse) {
3209   // Trivial replacement.
3210   if (V == Op)
3211     return RepOp;
3212 
3213   auto *I = dyn_cast<Instruction>(V);
3214   if (!I)
3215     return nullptr;
3216 
3217   // If this is a binary operator, try to simplify it with the replaced op.
3218   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3219     // Consider:
3220     //   %cmp = icmp eq i32 %x, 2147483647
3221     //   %add = add nsw i32 %x, 1
3222     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3223     //
3224     // We can't replace %sel with %add unless we strip away the flags.
3225     if (isa<OverflowingBinaryOperator>(B))
3226       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3227         return nullptr;
3228     if (isa<PossiblyExactOperator>(B))
3229       if (B->isExact())
3230         return nullptr;
3231 
3232     if (MaxRecurse) {
3233       if (B->getOperand(0) == Op)
3234         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3235                              MaxRecurse - 1);
3236       if (B->getOperand(1) == Op)
3237         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3238                              MaxRecurse - 1);
3239     }
3240   }
3241 
3242   // Same for CmpInsts.
3243   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3244     if (MaxRecurse) {
3245       if (C->getOperand(0) == Op)
3246         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3247                                MaxRecurse - 1);
3248       if (C->getOperand(1) == Op)
3249         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3250                                MaxRecurse - 1);
3251     }
3252   }
3253 
3254   // TODO: We could hand off more cases to instsimplify here.
3255 
3256   // If all operands are constant after substituting Op for RepOp then we can
3257   // constant fold the instruction.
3258   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3259     // Build a list of all constant operands.
3260     SmallVector<Constant *, 8> ConstOps;
3261     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3262       if (I->getOperand(i) == Op)
3263         ConstOps.push_back(CRepOp);
3264       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3265         ConstOps.push_back(COp);
3266       else
3267         break;
3268     }
3269 
3270     // All operands were constants, fold it.
3271     if (ConstOps.size() == I->getNumOperands()) {
3272       if (CmpInst *C = dyn_cast<CmpInst>(I))
3273         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3274                                                ConstOps[1], Q.DL, Q.TLI);
3275 
3276       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3277         if (!LI->isVolatile())
3278           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3279 
3280       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3281     }
3282   }
3283 
3284   return nullptr;
3285 }
3286 
3287 /// Given operands for a SelectInst, see if we can fold the result.
3288 /// If not, this returns null.
3289 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3290                                  Value *FalseVal, const Query &Q,
3291                                  unsigned MaxRecurse) {
3292   // select true, X, Y  -> X
3293   // select false, X, Y -> Y
3294   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3295     if (CB->isAllOnesValue())
3296       return TrueVal;
3297     if (CB->isNullValue())
3298       return FalseVal;
3299   }
3300 
3301   // select C, X, X -> X
3302   if (TrueVal == FalseVal)
3303     return TrueVal;
3304 
3305   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3306     if (isa<Constant>(TrueVal))
3307       return TrueVal;
3308     return FalseVal;
3309   }
3310   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3311     return FalseVal;
3312   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3313     return TrueVal;
3314 
3315   if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3316     unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
3317     ICmpInst::Predicate Pred = ICI->getPredicate();
3318     Value *CmpLHS = ICI->getOperand(0);
3319     Value *CmpRHS = ICI->getOperand(1);
3320     APInt MinSignedValue = APInt::getSignBit(BitWidth);
3321     Value *X;
3322     const APInt *Y;
3323     bool TrueWhenUnset;
3324     bool IsBitTest = false;
3325     if (ICmpInst::isEquality(Pred) &&
3326         match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3327         match(CmpRHS, m_Zero())) {
3328       IsBitTest = true;
3329       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
3330     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3331       X = CmpLHS;
3332       Y = &MinSignedValue;
3333       IsBitTest = true;
3334       TrueWhenUnset = false;
3335     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3336       X = CmpLHS;
3337       Y = &MinSignedValue;
3338       IsBitTest = true;
3339       TrueWhenUnset = true;
3340     }
3341     if (IsBitTest) {
3342       const APInt *C;
3343       // (X & Y) == 0 ? X & ~Y : X  --> X
3344       // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3345       if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3346           *Y == ~*C)
3347         return TrueWhenUnset ? FalseVal : TrueVal;
3348       // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3349       // (X & Y) != 0 ? X : X & ~Y  --> X
3350       if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3351           *Y == ~*C)
3352         return TrueWhenUnset ? FalseVal : TrueVal;
3353 
3354       if (Y->isPowerOf2()) {
3355         // (X & Y) == 0 ? X | Y : X  --> X | Y
3356         // (X & Y) != 0 ? X | Y : X  --> X
3357         if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3358             *Y == *C)
3359           return TrueWhenUnset ? TrueVal : FalseVal;
3360         // (X & Y) == 0 ? X : X | Y  --> X
3361         // (X & Y) != 0 ? X : X | Y  --> X | Y
3362         if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3363             *Y == *C)
3364           return TrueWhenUnset ? TrueVal : FalseVal;
3365       }
3366     }
3367     if (ICI->hasOneUse()) {
3368       const APInt *C;
3369       if (match(CmpRHS, m_APInt(C))) {
3370         // X < MIN ? T : F  -->  F
3371         if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3372           return FalseVal;
3373         // X < MIN ? T : F  -->  F
3374         if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3375           return FalseVal;
3376         // X > MAX ? T : F  -->  F
3377         if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3378           return FalseVal;
3379         // X > MAX ? T : F  -->  F
3380         if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3381           return FalseVal;
3382       }
3383     }
3384 
3385     // If we have an equality comparison then we know the value in one of the
3386     // arms of the select. See if substituting this value into the arm and
3387     // simplifying the result yields the same value as the other arm.
3388     if (Pred == ICmpInst::ICMP_EQ) {
3389       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3390               TrueVal ||
3391           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3392               TrueVal)
3393         return FalseVal;
3394       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3395               FalseVal ||
3396           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3397               FalseVal)
3398         return FalseVal;
3399     } else if (Pred == ICmpInst::ICMP_NE) {
3400       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3401               FalseVal ||
3402           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3403               FalseVal)
3404         return TrueVal;
3405       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3406               TrueVal ||
3407           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3408               TrueVal)
3409         return TrueVal;
3410     }
3411   }
3412 
3413   return nullptr;
3414 }
3415 
3416 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3417                                 const DataLayout &DL,
3418                                 const TargetLibraryInfo *TLI,
3419                                 const DominatorTree *DT, AssumptionCache *AC,
3420                                 const Instruction *CxtI) {
3421   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3422                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3423 }
3424 
3425 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3426 /// If not, this returns null.
3427 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3428                               const Query &Q, unsigned) {
3429   // The type of the GEP pointer operand.
3430   unsigned AS =
3431       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3432 
3433   // getelementptr P -> P.
3434   if (Ops.size() == 1)
3435     return Ops[0];
3436 
3437   // Compute the (pointer) type returned by the GEP instruction.
3438   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3439   Type *GEPTy = PointerType::get(LastType, AS);
3440   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3441     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3442 
3443   if (isa<UndefValue>(Ops[0]))
3444     return UndefValue::get(GEPTy);
3445 
3446   if (Ops.size() == 2) {
3447     // getelementptr P, 0 -> P.
3448     if (match(Ops[1], m_Zero()))
3449       return Ops[0];
3450 
3451     Type *Ty = SrcTy;
3452     if (Ty->isSized()) {
3453       Value *P;
3454       uint64_t C;
3455       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3456       // getelementptr P, N -> P if P points to a type of zero size.
3457       if (TyAllocSize == 0)
3458         return Ops[0];
3459 
3460       // The following transforms are only safe if the ptrtoint cast
3461       // doesn't truncate the pointers.
3462       if (Ops[1]->getType()->getScalarSizeInBits() ==
3463           Q.DL.getPointerSizeInBits(AS)) {
3464         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3465           if (match(P, m_Zero()))
3466             return Constant::getNullValue(GEPTy);
3467           Value *Temp;
3468           if (match(P, m_PtrToInt(m_Value(Temp))))
3469             if (Temp->getType() == GEPTy)
3470               return Temp;
3471           return nullptr;
3472         };
3473 
3474         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3475         if (TyAllocSize == 1 &&
3476             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3477           if (Value *R = PtrToIntOrZero(P))
3478             return R;
3479 
3480         // getelementptr V, (ashr (sub P, V), C) -> Q
3481         // if P points to a type of size 1 << C.
3482         if (match(Ops[1],
3483                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3484                          m_ConstantInt(C))) &&
3485             TyAllocSize == 1ULL << C)
3486           if (Value *R = PtrToIntOrZero(P))
3487             return R;
3488 
3489         // getelementptr V, (sdiv (sub P, V), C) -> Q
3490         // if P points to a type of size C.
3491         if (match(Ops[1],
3492                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3493                          m_SpecificInt(TyAllocSize))))
3494           if (Value *R = PtrToIntOrZero(P))
3495             return R;
3496       }
3497     }
3498   }
3499 
3500   // Check to see if this is constant foldable.
3501   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3502     if (!isa<Constant>(Ops[i]))
3503       return nullptr;
3504 
3505   return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3506                                         Ops.slice(1));
3507 }
3508 
3509 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3510                              const DataLayout &DL,
3511                              const TargetLibraryInfo *TLI,
3512                              const DominatorTree *DT, AssumptionCache *AC,
3513                              const Instruction *CxtI) {
3514   return ::SimplifyGEPInst(SrcTy, Ops,
3515                            Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3516 }
3517 
3518 /// Given operands for an InsertValueInst, see if we can fold the result.
3519 /// If not, this returns null.
3520 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3521                                       ArrayRef<unsigned> Idxs, const Query &Q,
3522                                       unsigned) {
3523   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3524     if (Constant *CVal = dyn_cast<Constant>(Val))
3525       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3526 
3527   // insertvalue x, undef, n -> x
3528   if (match(Val, m_Undef()))
3529     return Agg;
3530 
3531   // insertvalue x, (extractvalue y, n), n
3532   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3533     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3534         EV->getIndices() == Idxs) {
3535       // insertvalue undef, (extractvalue y, n), n -> y
3536       if (match(Agg, m_Undef()))
3537         return EV->getAggregateOperand();
3538 
3539       // insertvalue y, (extractvalue y, n), n -> y
3540       if (Agg == EV->getAggregateOperand())
3541         return Agg;
3542     }
3543 
3544   return nullptr;
3545 }
3546 
3547 Value *llvm::SimplifyInsertValueInst(
3548     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3549     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3550     const Instruction *CxtI) {
3551   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3552                                    RecursionLimit);
3553 }
3554 
3555 /// Given operands for an ExtractValueInst, see if we can fold the result.
3556 /// If not, this returns null.
3557 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3558                                        const Query &, unsigned) {
3559   if (auto *CAgg = dyn_cast<Constant>(Agg))
3560     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3561 
3562   // extractvalue x, (insertvalue y, elt, n), n -> elt
3563   unsigned NumIdxs = Idxs.size();
3564   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3565        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3566     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3567     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3568     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3569     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3570         Idxs.slice(0, NumCommonIdxs)) {
3571       if (NumIdxs == NumInsertValueIdxs)
3572         return IVI->getInsertedValueOperand();
3573       break;
3574     }
3575   }
3576 
3577   return nullptr;
3578 }
3579 
3580 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3581                                       const DataLayout &DL,
3582                                       const TargetLibraryInfo *TLI,
3583                                       const DominatorTree *DT,
3584                                       AssumptionCache *AC,
3585                                       const Instruction *CxtI) {
3586   return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3587                                     RecursionLimit);
3588 }
3589 
3590 /// Given operands for an ExtractElementInst, see if we can fold the result.
3591 /// If not, this returns null.
3592 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3593                                          unsigned) {
3594   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3595     if (auto *CIdx = dyn_cast<Constant>(Idx))
3596       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3597 
3598     // The index is not relevant if our vector is a splat.
3599     if (auto *Splat = CVec->getSplatValue())
3600       return Splat;
3601 
3602     if (isa<UndefValue>(Vec))
3603       return UndefValue::get(Vec->getType()->getVectorElementType());
3604   }
3605 
3606   // If extracting a specified index from the vector, see if we can recursively
3607   // find a previously computed scalar that was inserted into the vector.
3608   if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3609     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3610       return Elt;
3611 
3612   return nullptr;
3613 }
3614 
3615 Value *llvm::SimplifyExtractElementInst(
3616     Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3617     const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3618   return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3619                                       RecursionLimit);
3620 }
3621 
3622 /// See if we can fold the given phi. If not, returns null.
3623 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3624   // If all of the PHI's incoming values are the same then replace the PHI node
3625   // with the common value.
3626   Value *CommonValue = nullptr;
3627   bool HasUndefInput = false;
3628   for (Value *Incoming : PN->incoming_values()) {
3629     // If the incoming value is the phi node itself, it can safely be skipped.
3630     if (Incoming == PN) continue;
3631     if (isa<UndefValue>(Incoming)) {
3632       // Remember that we saw an undef value, but otherwise ignore them.
3633       HasUndefInput = true;
3634       continue;
3635     }
3636     if (CommonValue && Incoming != CommonValue)
3637       return nullptr;  // Not the same, bail out.
3638     CommonValue = Incoming;
3639   }
3640 
3641   // If CommonValue is null then all of the incoming values were either undef or
3642   // equal to the phi node itself.
3643   if (!CommonValue)
3644     return UndefValue::get(PN->getType());
3645 
3646   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3647   // instruction, we cannot return X as the result of the PHI node unless it
3648   // dominates the PHI block.
3649   if (HasUndefInput)
3650     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3651 
3652   return CommonValue;
3653 }
3654 
3655 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3656   if (Constant *C = dyn_cast<Constant>(Op))
3657     return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
3658 
3659   return nullptr;
3660 }
3661 
3662 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
3663                                const TargetLibraryInfo *TLI,
3664                                const DominatorTree *DT, AssumptionCache *AC,
3665                                const Instruction *CxtI) {
3666   return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3667                              RecursionLimit);
3668 }
3669 
3670 //=== Helper functions for higher up the class hierarchy.
3671 
3672 /// Given operands for a BinaryOperator, see if we can fold the result.
3673 /// If not, this returns null.
3674 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3675                             const Query &Q, unsigned MaxRecurse) {
3676   switch (Opcode) {
3677   case Instruction::Add:
3678     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3679                            Q, MaxRecurse);
3680   case Instruction::FAdd:
3681     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3682 
3683   case Instruction::Sub:
3684     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3685                            Q, MaxRecurse);
3686   case Instruction::FSub:
3687     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3688 
3689   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3690   case Instruction::FMul:
3691     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3692   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3693   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3694   case Instruction::FDiv:
3695       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3696   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3697   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3698   case Instruction::FRem:
3699       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3700   case Instruction::Shl:
3701     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3702                            Q, MaxRecurse);
3703   case Instruction::LShr:
3704     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3705   case Instruction::AShr:
3706     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3707   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3708   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3709   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3710   default:
3711     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3712       if (Constant *CRHS = dyn_cast<Constant>(RHS))
3713         return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3714 
3715     // If the operation is associative, try some generic simplifications.
3716     if (Instruction::isAssociative(Opcode))
3717       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3718         return V;
3719 
3720     // If the operation is with the result of a select instruction check whether
3721     // operating on either branch of the select always yields the same value.
3722     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3723       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3724         return V;
3725 
3726     // If the operation is with the result of a phi instruction, check whether
3727     // operating on all incoming values of the phi always yields the same value.
3728     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3729       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3730         return V;
3731 
3732     return nullptr;
3733   }
3734 }
3735 
3736 /// Given operands for a BinaryOperator, see if we can fold the result.
3737 /// If not, this returns null.
3738 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3739 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3740 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3741                               const FastMathFlags &FMF, const Query &Q,
3742                               unsigned MaxRecurse) {
3743   switch (Opcode) {
3744   case Instruction::FAdd:
3745     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3746   case Instruction::FSub:
3747     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3748   case Instruction::FMul:
3749     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3750   default:
3751     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3752   }
3753 }
3754 
3755 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3756                            const DataLayout &DL, const TargetLibraryInfo *TLI,
3757                            const DominatorTree *DT, AssumptionCache *AC,
3758                            const Instruction *CxtI) {
3759   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3760                          RecursionLimit);
3761 }
3762 
3763 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3764                              const FastMathFlags &FMF, const DataLayout &DL,
3765                              const TargetLibraryInfo *TLI,
3766                              const DominatorTree *DT, AssumptionCache *AC,
3767                              const Instruction *CxtI) {
3768   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3769                            RecursionLimit);
3770 }
3771 
3772 /// Given operands for a CmpInst, see if we can fold the result.
3773 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3774                               const Query &Q, unsigned MaxRecurse) {
3775   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3776     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3777   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3778 }
3779 
3780 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3781                              const DataLayout &DL, const TargetLibraryInfo *TLI,
3782                              const DominatorTree *DT, AssumptionCache *AC,
3783                              const Instruction *CxtI) {
3784   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3785                            RecursionLimit);
3786 }
3787 
3788 static bool IsIdempotent(Intrinsic::ID ID) {
3789   switch (ID) {
3790   default: return false;
3791 
3792   // Unary idempotent: f(f(x)) = f(x)
3793   case Intrinsic::fabs:
3794   case Intrinsic::floor:
3795   case Intrinsic::ceil:
3796   case Intrinsic::trunc:
3797   case Intrinsic::rint:
3798   case Intrinsic::nearbyint:
3799   case Intrinsic::round:
3800     return true;
3801   }
3802 }
3803 
3804 template <typename IterTy>
3805 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
3806                                 const Query &Q, unsigned MaxRecurse) {
3807   Intrinsic::ID IID = F->getIntrinsicID();
3808   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3809   Type *ReturnType = F->getReturnType();
3810 
3811   // Binary Ops
3812   if (NumOperands == 2) {
3813     Value *LHS = *ArgBegin;
3814     Value *RHS = *(ArgBegin + 1);
3815     if (IID == Intrinsic::usub_with_overflow ||
3816         IID == Intrinsic::ssub_with_overflow) {
3817       // X - X -> { 0, false }
3818       if (LHS == RHS)
3819         return Constant::getNullValue(ReturnType);
3820 
3821       // X - undef -> undef
3822       // undef - X -> undef
3823       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3824         return UndefValue::get(ReturnType);
3825     }
3826 
3827     if (IID == Intrinsic::uadd_with_overflow ||
3828         IID == Intrinsic::sadd_with_overflow) {
3829       // X + undef -> undef
3830       if (isa<UndefValue>(RHS))
3831         return UndefValue::get(ReturnType);
3832     }
3833 
3834     if (IID == Intrinsic::umul_with_overflow ||
3835         IID == Intrinsic::smul_with_overflow) {
3836       // X * 0 -> { 0, false }
3837       if (match(RHS, m_Zero()))
3838         return Constant::getNullValue(ReturnType);
3839 
3840       // X * undef -> { 0, false }
3841       if (match(RHS, m_Undef()))
3842         return Constant::getNullValue(ReturnType);
3843     }
3844   }
3845 
3846   // Perform idempotent optimizations
3847   if (!IsIdempotent(IID))
3848     return nullptr;
3849 
3850   // Unary Ops
3851   if (NumOperands == 1)
3852     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3853       if (II->getIntrinsicID() == IID)
3854         return II;
3855 
3856   return nullptr;
3857 }
3858 
3859 template <typename IterTy>
3860 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3861                            const Query &Q, unsigned MaxRecurse) {
3862   Type *Ty = V->getType();
3863   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3864     Ty = PTy->getElementType();
3865   FunctionType *FTy = cast<FunctionType>(Ty);
3866 
3867   // call undef -> undef
3868   if (isa<UndefValue>(V))
3869     return UndefValue::get(FTy->getReturnType());
3870 
3871   Function *F = dyn_cast<Function>(V);
3872   if (!F)
3873     return nullptr;
3874 
3875   if (F->isIntrinsic())
3876     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
3877       return Ret;
3878 
3879   if (!canConstantFoldCallTo(F))
3880     return nullptr;
3881 
3882   SmallVector<Constant *, 4> ConstantArgs;
3883   ConstantArgs.reserve(ArgEnd - ArgBegin);
3884   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3885     Constant *C = dyn_cast<Constant>(*I);
3886     if (!C)
3887       return nullptr;
3888     ConstantArgs.push_back(C);
3889   }
3890 
3891   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3892 }
3893 
3894 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3895                           User::op_iterator ArgEnd, const DataLayout &DL,
3896                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
3897                           AssumptionCache *AC, const Instruction *CxtI) {
3898   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
3899                         RecursionLimit);
3900 }
3901 
3902 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3903                           const DataLayout &DL, const TargetLibraryInfo *TLI,
3904                           const DominatorTree *DT, AssumptionCache *AC,
3905                           const Instruction *CxtI) {
3906   return ::SimplifyCall(V, Args.begin(), Args.end(),
3907                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3908 }
3909 
3910 /// See if we can compute a simplified version of this instruction.
3911 /// If not, this returns null.
3912 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
3913                                  const TargetLibraryInfo *TLI,
3914                                  const DominatorTree *DT, AssumptionCache *AC) {
3915   Value *Result;
3916 
3917   switch (I->getOpcode()) {
3918   default:
3919     Result = ConstantFoldInstruction(I, DL, TLI);
3920     break;
3921   case Instruction::FAdd:
3922     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3923                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
3924     break;
3925   case Instruction::Add:
3926     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3927                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3928                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
3929                              TLI, DT, AC, I);
3930     break;
3931   case Instruction::FSub:
3932     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3933                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
3934     break;
3935   case Instruction::Sub:
3936     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3937                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3938                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
3939                              TLI, DT, AC, I);
3940     break;
3941   case Instruction::FMul:
3942     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3943                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
3944     break;
3945   case Instruction::Mul:
3946     Result =
3947         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
3948     break;
3949   case Instruction::SDiv:
3950     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3951                               AC, I);
3952     break;
3953   case Instruction::UDiv:
3954     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3955                               AC, I);
3956     break;
3957   case Instruction::FDiv:
3958     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3959                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
3960     break;
3961   case Instruction::SRem:
3962     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3963                               AC, I);
3964     break;
3965   case Instruction::URem:
3966     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3967                               AC, I);
3968     break;
3969   case Instruction::FRem:
3970     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3971                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
3972     break;
3973   case Instruction::Shl:
3974     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3975                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3976                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
3977                              TLI, DT, AC, I);
3978     break;
3979   case Instruction::LShr:
3980     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3981                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
3982                               AC, I);
3983     break;
3984   case Instruction::AShr:
3985     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3986                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
3987                               AC, I);
3988     break;
3989   case Instruction::And:
3990     Result =
3991         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
3992     break;
3993   case Instruction::Or:
3994     Result =
3995         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
3996     break;
3997   case Instruction::Xor:
3998     Result =
3999         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4000     break;
4001   case Instruction::ICmp:
4002     Result =
4003         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4004                          I->getOperand(1), DL, TLI, DT, AC, I);
4005     break;
4006   case Instruction::FCmp:
4007     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4008                               I->getOperand(0), I->getOperand(1),
4009                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4010     break;
4011   case Instruction::Select:
4012     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4013                                 I->getOperand(2), DL, TLI, DT, AC, I);
4014     break;
4015   case Instruction::GetElementPtr: {
4016     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4017     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4018                              Ops, DL, TLI, DT, AC, I);
4019     break;
4020   }
4021   case Instruction::InsertValue: {
4022     InsertValueInst *IV = cast<InsertValueInst>(I);
4023     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4024                                      IV->getInsertedValueOperand(),
4025                                      IV->getIndices(), DL, TLI, DT, AC, I);
4026     break;
4027   }
4028   case Instruction::ExtractValue: {
4029     auto *EVI = cast<ExtractValueInst>(I);
4030     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4031                                       EVI->getIndices(), DL, TLI, DT, AC, I);
4032     break;
4033   }
4034   case Instruction::ExtractElement: {
4035     auto *EEI = cast<ExtractElementInst>(I);
4036     Result = SimplifyExtractElementInst(
4037         EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4038     break;
4039   }
4040   case Instruction::PHI:
4041     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4042     break;
4043   case Instruction::Call: {
4044     CallSite CS(cast<CallInst>(I));
4045     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4046                           TLI, DT, AC, I);
4047     break;
4048   }
4049   case Instruction::Trunc:
4050     Result =
4051         SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
4052     break;
4053   }
4054 
4055   // In general, it is possible for computeKnownBits to determine all bits in a
4056   // value even when the operands are not all constants.
4057   if (!Result && I->getType()->isIntegerTy()) {
4058     unsigned BitWidth = I->getType()->getScalarSizeInBits();
4059     APInt KnownZero(BitWidth, 0);
4060     APInt KnownOne(BitWidth, 0);
4061     computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4062     if ((KnownZero | KnownOne).isAllOnesValue())
4063       Result = ConstantInt::get(I->getContext(), KnownOne);
4064   }
4065 
4066   /// If called on unreachable code, the above logic may report that the
4067   /// instruction simplified to itself.  Make life easier for users by
4068   /// detecting that case here, returning a safe value instead.
4069   return Result == I ? UndefValue::get(I->getType()) : Result;
4070 }
4071 
4072 /// \brief Implementation of recursive simplification through an instruction's
4073 /// uses.
4074 ///
4075 /// This is the common implementation of the recursive simplification routines.
4076 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4077 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4078 /// instructions to process and attempt to simplify it using
4079 /// InstructionSimplify.
4080 ///
4081 /// This routine returns 'true' only when *it* simplifies something. The passed
4082 /// in simplified value does not count toward this.
4083 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4084                                               const TargetLibraryInfo *TLI,
4085                                               const DominatorTree *DT,
4086                                               AssumptionCache *AC) {
4087   bool Simplified = false;
4088   SmallSetVector<Instruction *, 8> Worklist;
4089   const DataLayout &DL = I->getModule()->getDataLayout();
4090 
4091   // If we have an explicit value to collapse to, do that round of the
4092   // simplification loop by hand initially.
4093   if (SimpleV) {
4094     for (User *U : I->users())
4095       if (U != I)
4096         Worklist.insert(cast<Instruction>(U));
4097 
4098     // Replace the instruction with its simplified value.
4099     I->replaceAllUsesWith(SimpleV);
4100 
4101     // Gracefully handle edge cases where the instruction is not wired into any
4102     // parent block.
4103     if (I->getParent())
4104       I->eraseFromParent();
4105   } else {
4106     Worklist.insert(I);
4107   }
4108 
4109   // Note that we must test the size on each iteration, the worklist can grow.
4110   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4111     I = Worklist[Idx];
4112 
4113     // See if this instruction simplifies.
4114     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4115     if (!SimpleV)
4116       continue;
4117 
4118     Simplified = true;
4119 
4120     // Stash away all the uses of the old instruction so we can check them for
4121     // recursive simplifications after a RAUW. This is cheaper than checking all
4122     // uses of To on the recursive step in most cases.
4123     for (User *U : I->users())
4124       Worklist.insert(cast<Instruction>(U));
4125 
4126     // Replace the instruction with its simplified value.
4127     I->replaceAllUsesWith(SimpleV);
4128 
4129     // Gracefully handle edge cases where the instruction is not wired into any
4130     // parent block.
4131     if (I->getParent())
4132       I->eraseFromParent();
4133   }
4134   return Simplified;
4135 }
4136 
4137 bool llvm::recursivelySimplifyInstruction(Instruction *I,
4138                                           const TargetLibraryInfo *TLI,
4139                                           const DominatorTree *DT,
4140                                           AssumptionCache *AC) {
4141   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4142 }
4143 
4144 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4145                                          const TargetLibraryInfo *TLI,
4146                                          const DominatorTree *DT,
4147                                          AssumptionCache *AC) {
4148   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4149   assert(SimpleV && "Must provide a simplified value.");
4150   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
4151 }
4152