1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions.  This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/InstructionSimplify.h"
20 
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/Analysis/CmpInstAnalysis.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/InstSimplifyFolder.h"
30 #include "llvm/Analysis/LoopAnalysisManager.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/OverflowInstAnalysis.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/ConstantRange.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/PatternMatch.h"
42 #include "llvm/Support/KnownBits.h"
43 #include <algorithm>
44 using namespace llvm;
45 using namespace llvm::PatternMatch;
46 
47 #define DEBUG_TYPE "instsimplify"
48 
49 enum { RecursionLimit = 3 };
50 
51 STATISTIC(NumExpand, "Number of expansions");
52 STATISTIC(NumReassoc, "Number of reassociations");
53 
54 static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
55                               unsigned);
56 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
57 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
58                              const SimplifyQuery &, unsigned);
59 static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
60                             unsigned);
61 static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
62                             const SimplifyQuery &, unsigned);
63 static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
64                               unsigned);
65 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
66                                const SimplifyQuery &Q, unsigned MaxRecurse);
67 static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
68 static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
69                               unsigned);
70 static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
71                                unsigned);
72 static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
73                               const SimplifyQuery &, unsigned);
74 static Value *simplifySelectInst(Value *, Value *, Value *,
75                                  const SimplifyQuery &, unsigned);
76 
77 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
78                                      Value *FalseVal) {
79   BinaryOperator::BinaryOps BinOpCode;
80   if (auto *BO = dyn_cast<BinaryOperator>(Cond))
81     BinOpCode = BO->getOpcode();
82   else
83     return nullptr;
84 
85   CmpInst::Predicate ExpectedPred, Pred1, Pred2;
86   if (BinOpCode == BinaryOperator::Or) {
87     ExpectedPred = ICmpInst::ICMP_NE;
88   } else if (BinOpCode == BinaryOperator::And) {
89     ExpectedPred = ICmpInst::ICMP_EQ;
90   } else
91     return nullptr;
92 
93   // %A = icmp eq %TV, %FV
94   // %B = icmp eq %X, %Y (and one of these is a select operand)
95   // %C = and %A, %B
96   // %D = select %C, %TV, %FV
97   // -->
98   // %FV
99 
100   // %A = icmp ne %TV, %FV
101   // %B = icmp ne %X, %Y (and one of these is a select operand)
102   // %C = or %A, %B
103   // %D = select %C, %TV, %FV
104   // -->
105   // %TV
106   Value *X, *Y;
107   if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
108                                       m_Specific(FalseVal)),
109                              m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
110       Pred1 != Pred2 || Pred1 != ExpectedPred)
111     return nullptr;
112 
113   if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
114     return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
115 
116   return nullptr;
117 }
118 
119 /// For a boolean type or a vector of boolean type, return false or a vector
120 /// with every element false.
121 static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
122 
123 /// For a boolean type or a vector of boolean type, return true or a vector
124 /// with every element true.
125 static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
126 
127 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
128 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
129                           Value *RHS) {
130   CmpInst *Cmp = dyn_cast<CmpInst>(V);
131   if (!Cmp)
132     return false;
133   CmpInst::Predicate CPred = Cmp->getPredicate();
134   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
135   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
136     return true;
137   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
138          CRHS == LHS;
139 }
140 
141 /// Simplify comparison with true or false branch of select:
142 ///  %sel = select i1 %cond, i32 %tv, i32 %fv
143 ///  %cmp = icmp sle i32 %sel, %rhs
144 /// Compose new comparison by substituting %sel with either %tv or %fv
145 /// and see if it simplifies.
146 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
147                                  Value *RHS, Value *Cond,
148                                  const SimplifyQuery &Q, unsigned MaxRecurse,
149                                  Constant *TrueOrFalse) {
150   Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
151   if (SimplifiedCmp == Cond) {
152     // %cmp simplified to the select condition (%cond).
153     return TrueOrFalse;
154   } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
155     // It didn't simplify. However, if composed comparison is equivalent
156     // to the select condition (%cond) then we can replace it.
157     return TrueOrFalse;
158   }
159   return SimplifiedCmp;
160 }
161 
162 /// Simplify comparison with true branch of select
163 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
164                                      Value *RHS, Value *Cond,
165                                      const SimplifyQuery &Q,
166                                      unsigned MaxRecurse) {
167   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
168                             getTrue(Cond->getType()));
169 }
170 
171 /// Simplify comparison with false branch of select
172 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
173                                       Value *RHS, Value *Cond,
174                                       const SimplifyQuery &Q,
175                                       unsigned MaxRecurse) {
176   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
177                             getFalse(Cond->getType()));
178 }
179 
180 /// We know comparison with both branches of select can be simplified, but they
181 /// are not equal. This routine handles some logical simplifications.
182 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
183                                                Value *Cond,
184                                                const SimplifyQuery &Q,
185                                                unsigned MaxRecurse) {
186   // If the false value simplified to false, then the result of the compare
187   // is equal to "Cond && TCmp".  This also catches the case when the false
188   // value simplified to false and the true value to true, returning "Cond".
189   // Folding select to and/or isn't poison-safe in general; impliesPoison
190   // checks whether folding it does not convert a well-defined value into
191   // poison.
192   if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
193     if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
194       return V;
195   // If the true value simplified to true, then the result of the compare
196   // is equal to "Cond || FCmp".
197   if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
198     if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
199       return V;
200   // Finally, if the false value simplified to true and the true value to
201   // false, then the result of the compare is equal to "!Cond".
202   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
203     if (Value *V = simplifyXorInst(
204             Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
205       return V;
206   return nullptr;
207 }
208 
209 /// Does the given value dominate the specified phi node?
210 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
211   Instruction *I = dyn_cast<Instruction>(V);
212   if (!I)
213     // Arguments and constants dominate all instructions.
214     return true;
215 
216   // If we are processing instructions (and/or basic blocks) that have not been
217   // fully added to a function, the parent nodes may still be null. Simply
218   // return the conservative answer in these cases.
219   if (!I->getParent() || !P->getParent() || !I->getFunction())
220     return false;
221 
222   // If we have a DominatorTree then do a precise test.
223   if (DT)
224     return DT->dominates(I, P);
225 
226   // Otherwise, if the instruction is in the entry block and is not an invoke,
227   // then it obviously dominates all phi nodes.
228   if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
229       !isa<CallBrInst>(I))
230     return true;
231 
232   return false;
233 }
234 
235 /// Try to simplify a binary operator of form "V op OtherOp" where V is
236 /// "(B0 opex B1)" by distributing 'op' across 'opex' as
237 /// "(B0 op OtherOp) opex (B1 op OtherOp)".
238 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
239                           Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
240                           const SimplifyQuery &Q, unsigned MaxRecurse) {
241   auto *B = dyn_cast<BinaryOperator>(V);
242   if (!B || B->getOpcode() != OpcodeToExpand)
243     return nullptr;
244   Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
245   Value *L =
246       simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
247   if (!L)
248     return nullptr;
249   Value *R =
250       simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
251   if (!R)
252     return nullptr;
253 
254   // Does the expanded pair of binops simplify to the existing binop?
255   if ((L == B0 && R == B1) ||
256       (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
257     ++NumExpand;
258     return B;
259   }
260 
261   // Otherwise, return "L op' R" if it simplifies.
262   Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
263   if (!S)
264     return nullptr;
265 
266   ++NumExpand;
267   return S;
268 }
269 
270 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
271 /// distributing op over op'.
272 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
273                                      Value *R,
274                                      Instruction::BinaryOps OpcodeToExpand,
275                                      const SimplifyQuery &Q,
276                                      unsigned MaxRecurse) {
277   // Recursion is always used, so bail out at once if we already hit the limit.
278   if (!MaxRecurse--)
279     return nullptr;
280 
281   if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
282     return V;
283   if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
284     return V;
285   return nullptr;
286 }
287 
288 /// Generic simplifications for associative binary operations.
289 /// Returns the simpler value, or null if none was found.
290 static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
291                                        Value *LHS, Value *RHS,
292                                        const SimplifyQuery &Q,
293                                        unsigned MaxRecurse) {
294   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
295 
296   // Recursion is always used, so bail out at once if we already hit the limit.
297   if (!MaxRecurse--)
298     return nullptr;
299 
300   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
301   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
302 
303   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
304   if (Op0 && Op0->getOpcode() == Opcode) {
305     Value *A = Op0->getOperand(0);
306     Value *B = Op0->getOperand(1);
307     Value *C = RHS;
308 
309     // Does "B op C" simplify?
310     if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
311       // It does!  Return "A op V" if it simplifies or is already available.
312       // If V equals B then "A op V" is just the LHS.
313       if (V == B)
314         return LHS;
315       // Otherwise return "A op V" if it simplifies.
316       if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
317         ++NumReassoc;
318         return W;
319       }
320     }
321   }
322 
323   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
324   if (Op1 && Op1->getOpcode() == Opcode) {
325     Value *A = LHS;
326     Value *B = Op1->getOperand(0);
327     Value *C = Op1->getOperand(1);
328 
329     // Does "A op B" simplify?
330     if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
331       // It does!  Return "V op C" if it simplifies or is already available.
332       // If V equals B then "V op C" is just the RHS.
333       if (V == B)
334         return RHS;
335       // Otherwise return "V op C" if it simplifies.
336       if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
337         ++NumReassoc;
338         return W;
339       }
340     }
341   }
342 
343   // The remaining transforms require commutativity as well as associativity.
344   if (!Instruction::isCommutative(Opcode))
345     return nullptr;
346 
347   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
348   if (Op0 && Op0->getOpcode() == Opcode) {
349     Value *A = Op0->getOperand(0);
350     Value *B = Op0->getOperand(1);
351     Value *C = RHS;
352 
353     // Does "C op A" simplify?
354     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
355       // It does!  Return "V op B" if it simplifies or is already available.
356       // If V equals A then "V op B" is just the LHS.
357       if (V == A)
358         return LHS;
359       // Otherwise return "V op B" if it simplifies.
360       if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
361         ++NumReassoc;
362         return W;
363       }
364     }
365   }
366 
367   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
368   if (Op1 && Op1->getOpcode() == Opcode) {
369     Value *A = LHS;
370     Value *B = Op1->getOperand(0);
371     Value *C = Op1->getOperand(1);
372 
373     // Does "C op A" simplify?
374     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
375       // It does!  Return "B op V" if it simplifies or is already available.
376       // If V equals C then "B op V" is just the RHS.
377       if (V == C)
378         return RHS;
379       // Otherwise return "B op V" if it simplifies.
380       if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
381         ++NumReassoc;
382         return W;
383       }
384     }
385   }
386 
387   return nullptr;
388 }
389 
390 /// In the case of a binary operation with a select instruction as an operand,
391 /// try to simplify the binop by seeing whether evaluating it on both branches
392 /// of the select results in the same value. Returns the common value if so,
393 /// otherwise returns null.
394 static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
395                                     Value *RHS, const SimplifyQuery &Q,
396                                     unsigned MaxRecurse) {
397   // Recursion is always used, so bail out at once if we already hit the limit.
398   if (!MaxRecurse--)
399     return nullptr;
400 
401   SelectInst *SI;
402   if (isa<SelectInst>(LHS)) {
403     SI = cast<SelectInst>(LHS);
404   } else {
405     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
406     SI = cast<SelectInst>(RHS);
407   }
408 
409   // Evaluate the BinOp on the true and false branches of the select.
410   Value *TV;
411   Value *FV;
412   if (SI == LHS) {
413     TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
414     FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
415   } else {
416     TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
417     FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
418   }
419 
420   // If they simplified to the same value, then return the common value.
421   // If they both failed to simplify then return null.
422   if (TV == FV)
423     return TV;
424 
425   // If one branch simplified to undef, return the other one.
426   if (TV && Q.isUndefValue(TV))
427     return FV;
428   if (FV && Q.isUndefValue(FV))
429     return TV;
430 
431   // If applying the operation did not change the true and false select values,
432   // then the result of the binop is the select itself.
433   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
434     return SI;
435 
436   // If one branch simplified and the other did not, and the simplified
437   // value is equal to the unsimplified one, return the simplified value.
438   // For example, select (cond, X, X & Z) & Z -> X & Z.
439   if ((FV && !TV) || (TV && !FV)) {
440     // Check that the simplified value has the form "X op Y" where "op" is the
441     // same as the original operation.
442     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
443     if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
444       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
445       // We already know that "op" is the same as for the simplified value.  See
446       // if the operands match too.  If so, return the simplified value.
447       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
448       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
449       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
450       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
451           Simplified->getOperand(1) == UnsimplifiedRHS)
452         return Simplified;
453       if (Simplified->isCommutative() &&
454           Simplified->getOperand(1) == UnsimplifiedLHS &&
455           Simplified->getOperand(0) == UnsimplifiedRHS)
456         return Simplified;
457     }
458   }
459 
460   return nullptr;
461 }
462 
463 /// In the case of a comparison with a select instruction, try to simplify the
464 /// comparison by seeing whether both branches of the select result in the same
465 /// value. Returns the common value if so, otherwise returns null.
466 /// For example, if we have:
467 ///  %tmp = select i1 %cmp, i32 1, i32 2
468 ///  %cmp1 = icmp sle i32 %tmp, 3
469 /// We can simplify %cmp1 to true, because both branches of select are
470 /// less than 3. We compose new comparison by substituting %tmp with both
471 /// branches of select and see if it can be simplified.
472 static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
473                                   Value *RHS, const SimplifyQuery &Q,
474                                   unsigned MaxRecurse) {
475   // Recursion is always used, so bail out at once if we already hit the limit.
476   if (!MaxRecurse--)
477     return nullptr;
478 
479   // Make sure the select is on the LHS.
480   if (!isa<SelectInst>(LHS)) {
481     std::swap(LHS, RHS);
482     Pred = CmpInst::getSwappedPredicate(Pred);
483   }
484   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
485   SelectInst *SI = cast<SelectInst>(LHS);
486   Value *Cond = SI->getCondition();
487   Value *TV = SI->getTrueValue();
488   Value *FV = SI->getFalseValue();
489 
490   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
491   // Does "cmp TV, RHS" simplify?
492   Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
493   if (!TCmp)
494     return nullptr;
495 
496   // Does "cmp FV, RHS" simplify?
497   Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
498   if (!FCmp)
499     return nullptr;
500 
501   // If both sides simplified to the same value, then use it as the result of
502   // the original comparison.
503   if (TCmp == FCmp)
504     return TCmp;
505 
506   // The remaining cases only make sense if the select condition has the same
507   // type as the result of the comparison, so bail out if this is not so.
508   if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
509     return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
510 
511   return nullptr;
512 }
513 
514 /// In the case of a binary operation with an operand that is a PHI instruction,
515 /// try to simplify the binop by seeing whether evaluating it on the incoming
516 /// phi values yields the same result for every value. If so returns the common
517 /// value, otherwise returns null.
518 static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
519                                  Value *RHS, const SimplifyQuery &Q,
520                                  unsigned MaxRecurse) {
521   // Recursion is always used, so bail out at once if we already hit the limit.
522   if (!MaxRecurse--)
523     return nullptr;
524 
525   PHINode *PI;
526   if (isa<PHINode>(LHS)) {
527     PI = cast<PHINode>(LHS);
528     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
529     if (!valueDominatesPHI(RHS, PI, Q.DT))
530       return nullptr;
531   } else {
532     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
533     PI = cast<PHINode>(RHS);
534     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
535     if (!valueDominatesPHI(LHS, PI, Q.DT))
536       return nullptr;
537   }
538 
539   // Evaluate the BinOp on the incoming phi values.
540   Value *CommonValue = nullptr;
541   for (Value *Incoming : PI->incoming_values()) {
542     // If the incoming value is the phi node itself, it can safely be skipped.
543     if (Incoming == PI)
544       continue;
545     Value *V = PI == LHS ? simplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse)
546                          : simplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
547     // If the operation failed to simplify, or simplified to a different value
548     // to previously, then give up.
549     if (!V || (CommonValue && V != CommonValue))
550       return nullptr;
551     CommonValue = V;
552   }
553 
554   return CommonValue;
555 }
556 
557 /// In the case of a comparison with a PHI instruction, try to simplify the
558 /// comparison by seeing whether comparing with all of the incoming phi values
559 /// yields the same result every time. If so returns the common result,
560 /// otherwise returns null.
561 static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
562                                const SimplifyQuery &Q, unsigned MaxRecurse) {
563   // Recursion is always used, so bail out at once if we already hit the limit.
564   if (!MaxRecurse--)
565     return nullptr;
566 
567   // Make sure the phi is on the LHS.
568   if (!isa<PHINode>(LHS)) {
569     std::swap(LHS, RHS);
570     Pred = CmpInst::getSwappedPredicate(Pred);
571   }
572   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
573   PHINode *PI = cast<PHINode>(LHS);
574 
575   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
576   if (!valueDominatesPHI(RHS, PI, Q.DT))
577     return nullptr;
578 
579   // Evaluate the BinOp on the incoming phi values.
580   Value *CommonValue = nullptr;
581   for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
582     Value *Incoming = PI->getIncomingValue(u);
583     Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
584     // If the incoming value is the phi node itself, it can safely be skipped.
585     if (Incoming == PI)
586       continue;
587     // Change the context instruction to the "edge" that flows into the phi.
588     // This is important because that is where incoming is actually "evaluated"
589     // even though it is used later somewhere else.
590     Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
591                                MaxRecurse);
592     // If the operation failed to simplify, or simplified to a different value
593     // to previously, then give up.
594     if (!V || (CommonValue && V != CommonValue))
595       return nullptr;
596     CommonValue = V;
597   }
598 
599   return CommonValue;
600 }
601 
602 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
603                                        Value *&Op0, Value *&Op1,
604                                        const SimplifyQuery &Q) {
605   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
606     if (auto *CRHS = dyn_cast<Constant>(Op1))
607       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
608 
609     // Canonicalize the constant to the RHS if this is a commutative operation.
610     if (Instruction::isCommutative(Opcode))
611       std::swap(Op0, Op1);
612   }
613   return nullptr;
614 }
615 
616 /// Given operands for an Add, see if we can fold the result.
617 /// If not, this returns null.
618 static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
619                               const SimplifyQuery &Q, unsigned MaxRecurse) {
620   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
621     return C;
622 
623   // X + poison -> poison
624   if (isa<PoisonValue>(Op1))
625     return Op1;
626 
627   // X + undef -> undef
628   if (Q.isUndefValue(Op1))
629     return Op1;
630 
631   // X + 0 -> X
632   if (match(Op1, m_Zero()))
633     return Op0;
634 
635   // If two operands are negative, return 0.
636   if (isKnownNegation(Op0, Op1))
637     return Constant::getNullValue(Op0->getType());
638 
639   // X + (Y - X) -> Y
640   // (Y - X) + X -> Y
641   // Eg: X + -X -> 0
642   Value *Y = nullptr;
643   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
644       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
645     return Y;
646 
647   // X + ~X -> -1   since   ~X = -X-1
648   Type *Ty = Op0->getType();
649   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
650     return Constant::getAllOnesValue(Ty);
651 
652   // add nsw/nuw (xor Y, signmask), signmask --> Y
653   // The no-wrapping add guarantees that the top bit will be set by the add.
654   // Therefore, the xor must be clearing the already set sign bit of Y.
655   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
656       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
657     return Y;
658 
659   // add nuw %x, -1  ->  -1, because %x can only be 0.
660   if (IsNUW && match(Op1, m_AllOnes()))
661     return Op1; // Which is -1.
662 
663   /// i1 add -> xor.
664   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
665     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
666       return V;
667 
668   // Try some generic simplifications for associative operations.
669   if (Value *V =
670           simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
671     return V;
672 
673   // Threading Add over selects and phi nodes is pointless, so don't bother.
674   // Threading over the select in "A + select(cond, B, C)" means evaluating
675   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
676   // only if B and C are equal.  If B and C are equal then (since we assume
677   // that operands have already been simplified) "select(cond, B, C)" should
678   // have been simplified to the common value of B and C already.  Analysing
679   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
680   // for threading over phi nodes.
681 
682   return nullptr;
683 }
684 
685 Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
686                              const SimplifyQuery &Query) {
687   return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
688 }
689 
690 /// Compute the base pointer and cumulative constant offsets for V.
691 ///
692 /// This strips all constant offsets off of V, leaving it the base pointer, and
693 /// accumulates the total constant offset applied in the returned constant.
694 /// It returns zero if there are no constant offsets applied.
695 ///
696 /// This is very similar to stripAndAccumulateConstantOffsets(), except it
697 /// normalizes the offset bitwidth to the stripped pointer type, not the
698 /// original pointer type.
699 static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
700                                             bool AllowNonInbounds = false) {
701   assert(V->getType()->isPtrOrPtrVectorTy());
702 
703   APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
704   V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
705   // As that strip may trace through `addrspacecast`, need to sext or trunc
706   // the offset calculated.
707   return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
708 }
709 
710 /// Compute the constant difference between two pointer values.
711 /// If the difference is not a constant, returns zero.
712 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
713                                           Value *RHS) {
714   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
715   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
716 
717   // If LHS and RHS are not related via constant offsets to the same base
718   // value, there is nothing we can do here.
719   if (LHS != RHS)
720     return nullptr;
721 
722   // Otherwise, the difference of LHS - RHS can be computed as:
723   //    LHS - RHS
724   //  = (LHSOffset + Base) - (RHSOffset + Base)
725   //  = LHSOffset - RHSOffset
726   Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
727   if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
728     Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
729   return Res;
730 }
731 
732 /// Given operands for a Sub, see if we can fold the result.
733 /// If not, this returns null.
734 static Value *simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
735                               const SimplifyQuery &Q, unsigned MaxRecurse) {
736   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
737     return C;
738 
739   // X - poison -> poison
740   // poison - X -> poison
741   if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
742     return PoisonValue::get(Op0->getType());
743 
744   // X - undef -> undef
745   // undef - X -> undef
746   if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
747     return UndefValue::get(Op0->getType());
748 
749   // X - 0 -> X
750   if (match(Op1, m_Zero()))
751     return Op0;
752 
753   // X - X -> 0
754   if (Op0 == Op1)
755     return Constant::getNullValue(Op0->getType());
756 
757   // Is this a negation?
758   if (match(Op0, m_Zero())) {
759     // 0 - X -> 0 if the sub is NUW.
760     if (isNUW)
761       return Constant::getNullValue(Op0->getType());
762 
763     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
764     if (Known.Zero.isMaxSignedValue()) {
765       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
766       // Op1 must be 0 because negating the minimum signed value is undefined.
767       if (isNSW)
768         return Constant::getNullValue(Op0->getType());
769 
770       // 0 - X -> X if X is 0 or the minimum signed value.
771       return Op1;
772     }
773   }
774 
775   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
776   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
777   Value *X = nullptr, *Y = nullptr, *Z = Op1;
778   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
779     // See if "V === Y - Z" simplifies.
780     if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
781       // It does!  Now see if "X + V" simplifies.
782       if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
783         // It does, we successfully reassociated!
784         ++NumReassoc;
785         return W;
786       }
787     // See if "V === X - Z" simplifies.
788     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
789       // It does!  Now see if "Y + V" simplifies.
790       if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
791         // It does, we successfully reassociated!
792         ++NumReassoc;
793         return W;
794       }
795   }
796 
797   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
798   // For example, X - (X + 1) -> -1
799   X = Op0;
800   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
801     // See if "V === X - Y" simplifies.
802     if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
803       // It does!  Now see if "V - Z" simplifies.
804       if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
805         // It does, we successfully reassociated!
806         ++NumReassoc;
807         return W;
808       }
809     // See if "V === X - Z" simplifies.
810     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
811       // It does!  Now see if "V - Y" simplifies.
812       if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
813         // It does, we successfully reassociated!
814         ++NumReassoc;
815         return W;
816       }
817   }
818 
819   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
820   // For example, X - (X - Y) -> Y.
821   Z = Op0;
822   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
823     // See if "V === Z - X" simplifies.
824     if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
825       // It does!  Now see if "V + Y" simplifies.
826       if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
827         // It does, we successfully reassociated!
828         ++NumReassoc;
829         return W;
830       }
831 
832   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
833   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
834       match(Op1, m_Trunc(m_Value(Y))))
835     if (X->getType() == Y->getType())
836       // See if "V === X - Y" simplifies.
837       if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
838         // It does!  Now see if "trunc V" simplifies.
839         if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
840                                         Q, MaxRecurse - 1))
841           // It does, return the simplified "trunc V".
842           return W;
843 
844   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
845   if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
846     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
847       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
848 
849   // i1 sub -> xor.
850   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
851     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
852       return V;
853 
854   // Threading Sub over selects and phi nodes is pointless, so don't bother.
855   // Threading over the select in "A - select(cond, B, C)" means evaluating
856   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
857   // only if B and C are equal.  If B and C are equal then (since we assume
858   // that operands have already been simplified) "select(cond, B, C)" should
859   // have been simplified to the common value of B and C already.  Analysing
860   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
861   // for threading over phi nodes.
862 
863   return nullptr;
864 }
865 
866 Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
867                              const SimplifyQuery &Q) {
868   return ::simplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
869 }
870 
871 /// Given operands for a Mul, see if we can fold the result.
872 /// If not, this returns null.
873 static Value *simplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
874                               unsigned MaxRecurse) {
875   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
876     return C;
877 
878   // X * poison -> poison
879   if (isa<PoisonValue>(Op1))
880     return Op1;
881 
882   // X * undef -> 0
883   // X * 0 -> 0
884   if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
885     return Constant::getNullValue(Op0->getType());
886 
887   // X * 1 -> X
888   if (match(Op1, m_One()))
889     return Op0;
890 
891   // (X / Y) * Y -> X if the division is exact.
892   Value *X = nullptr;
893   if (Q.IIQ.UseInstrInfo &&
894       (match(Op0,
895              m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) ||     // (X / Y) * Y
896        match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
897     return X;
898 
899   // i1 mul -> and.
900   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
901     if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
902       return V;
903 
904   // Try some generic simplifications for associative operations.
905   if (Value *V =
906           simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
907     return V;
908 
909   // Mul distributes over Add. Try some generic simplifications based on this.
910   if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
911                                         Instruction::Add, Q, MaxRecurse))
912     return V;
913 
914   // If the operation is with the result of a select instruction, check whether
915   // operating on either branch of the select always yields the same value.
916   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
917     if (Value *V =
918             threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
919       return V;
920 
921   // If the operation is with the result of a phi instruction, check whether
922   // operating on all incoming values of the phi always yields the same value.
923   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
924     if (Value *V =
925             threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
926       return V;
927 
928   return nullptr;
929 }
930 
931 Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
932   return ::simplifyMulInst(Op0, Op1, Q, RecursionLimit);
933 }
934 
935 /// Check for common or similar folds of integer division or integer remainder.
936 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
937 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
938                              Value *Op1, const SimplifyQuery &Q) {
939   bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
940   bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
941 
942   Type *Ty = Op0->getType();
943 
944   // X / undef -> poison
945   // X % undef -> poison
946   if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
947     return PoisonValue::get(Ty);
948 
949   // X / 0 -> poison
950   // X % 0 -> poison
951   // We don't need to preserve faults!
952   if (match(Op1, m_Zero()))
953     return PoisonValue::get(Ty);
954 
955   // If any element of a constant divisor fixed width vector is zero or undef
956   // the behavior is undefined and we can fold the whole op to poison.
957   auto *Op1C = dyn_cast<Constant>(Op1);
958   auto *VTy = dyn_cast<FixedVectorType>(Ty);
959   if (Op1C && VTy) {
960     unsigned NumElts = VTy->getNumElements();
961     for (unsigned i = 0; i != NumElts; ++i) {
962       Constant *Elt = Op1C->getAggregateElement(i);
963       if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
964         return PoisonValue::get(Ty);
965     }
966   }
967 
968   // poison / X -> poison
969   // poison % X -> poison
970   if (isa<PoisonValue>(Op0))
971     return Op0;
972 
973   // undef / X -> 0
974   // undef % X -> 0
975   if (Q.isUndefValue(Op0))
976     return Constant::getNullValue(Ty);
977 
978   // 0 / X -> 0
979   // 0 % X -> 0
980   if (match(Op0, m_Zero()))
981     return Constant::getNullValue(Op0->getType());
982 
983   // X / X -> 1
984   // X % X -> 0
985   if (Op0 == Op1)
986     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
987 
988   // X / 1 -> X
989   // X % 1 -> 0
990   // If this is a boolean op (single-bit element type), we can't have
991   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
992   // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
993   Value *X;
994   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
995       (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
996     return IsDiv ? Op0 : Constant::getNullValue(Ty);
997 
998   // If X * Y does not overflow, then:
999   //   X * Y / Y -> X
1000   //   X * Y % Y -> 0
1001   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1002     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1003     // The multiplication can't overflow if it is defined not to, or if
1004     // X == A / Y for some A.
1005     if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1006         (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1007         (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1008         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1009       return IsDiv ? X : Constant::getNullValue(Op0->getType());
1010     }
1011   }
1012 
1013   return nullptr;
1014 }
1015 
1016 /// Given a predicate and two operands, return true if the comparison is true.
1017 /// This is a helper for div/rem simplification where we return some other value
1018 /// when we can prove a relationship between the operands.
1019 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
1020                        const SimplifyQuery &Q, unsigned MaxRecurse) {
1021   Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
1022   Constant *C = dyn_cast_or_null<Constant>(V);
1023   return (C && C->isAllOnesValue());
1024 }
1025 
1026 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
1027 /// to simplify X % Y to X.
1028 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
1029                       unsigned MaxRecurse, bool IsSigned) {
1030   // Recursion is always used, so bail out at once if we already hit the limit.
1031   if (!MaxRecurse--)
1032     return false;
1033 
1034   if (IsSigned) {
1035     // |X| / |Y| --> 0
1036     //
1037     // We require that 1 operand is a simple constant. That could be extended to
1038     // 2 variables if we computed the sign bit for each.
1039     //
1040     // Make sure that a constant is not the minimum signed value because taking
1041     // the abs() of that is undefined.
1042     Type *Ty = X->getType();
1043     const APInt *C;
1044     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1045       // Is the variable divisor magnitude always greater than the constant
1046       // dividend magnitude?
1047       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1048       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1049       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1050       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1051           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1052         return true;
1053     }
1054     if (match(Y, m_APInt(C))) {
1055       // Special-case: we can't take the abs() of a minimum signed value. If
1056       // that's the divisor, then all we have to do is prove that the dividend
1057       // is also not the minimum signed value.
1058       if (C->isMinSignedValue())
1059         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1060 
1061       // Is the variable dividend magnitude always less than the constant
1062       // divisor magnitude?
1063       // |X| < |C| --> X > -abs(C) and X < abs(C)
1064       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1065       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1066       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1067           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1068         return true;
1069     }
1070     return false;
1071   }
1072 
1073   // IsSigned == false.
1074 
1075   // Is the unsigned dividend known to be less than a constant divisor?
1076   // TODO: Convert this (and above) to range analysis
1077   //      ("computeConstantRangeIncludingKnownBits")?
1078   const APInt *C;
1079   if (match(Y, m_APInt(C)) &&
1080       computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
1081     return true;
1082 
1083   // Try again for any divisor:
1084   // Is the dividend unsigned less than the divisor?
1085   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1086 }
1087 
1088 /// These are simplifications common to SDiv and UDiv.
1089 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1090                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1091   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1092     return C;
1093 
1094   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
1095     return V;
1096 
1097   bool IsSigned = Opcode == Instruction::SDiv;
1098 
1099   // (X rem Y) / Y -> 0
1100   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1101       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1102     return Constant::getNullValue(Op0->getType());
1103 
1104   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1105   ConstantInt *C1, *C2;
1106   if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
1107       match(Op1, m_ConstantInt(C2))) {
1108     bool Overflow;
1109     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1110     if (Overflow)
1111       return Constant::getNullValue(Op0->getType());
1112   }
1113 
1114   // If the operation is with the result of a select instruction, check whether
1115   // operating on either branch of the select always yields the same value.
1116   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1117     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1118       return V;
1119 
1120   // If the operation is with the result of a phi instruction, check whether
1121   // operating on all incoming values of the phi always yields the same value.
1122   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1123     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1124       return V;
1125 
1126   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1127     return Constant::getNullValue(Op0->getType());
1128 
1129   return nullptr;
1130 }
1131 
1132 /// These are simplifications common to SRem and URem.
1133 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1134                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1135   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1136     return C;
1137 
1138   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
1139     return V;
1140 
1141   // (X % Y) % Y -> X % Y
1142   if ((Opcode == Instruction::SRem &&
1143        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1144       (Opcode == Instruction::URem &&
1145        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1146     return Op0;
1147 
1148   // (X << Y) % X -> 0
1149   if (Q.IIQ.UseInstrInfo &&
1150       ((Opcode == Instruction::SRem &&
1151         match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1152        (Opcode == Instruction::URem &&
1153         match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1154     return Constant::getNullValue(Op0->getType());
1155 
1156   // If the operation is with the result of a select instruction, check whether
1157   // operating on either branch of the select always yields the same value.
1158   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1159     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1160       return V;
1161 
1162   // If the operation is with the result of a phi instruction, check whether
1163   // operating on all incoming values of the phi always yields the same value.
1164   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1165     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1166       return V;
1167 
1168   // If X / Y == 0, then X % Y == X.
1169   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1170     return Op0;
1171 
1172   return nullptr;
1173 }
1174 
1175 /// Given operands for an SDiv, see if we can fold the result.
1176 /// If not, this returns null.
1177 static Value *simplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1178                                unsigned MaxRecurse) {
1179   // If two operands are negated and no signed overflow, return -1.
1180   if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1181     return Constant::getAllOnesValue(Op0->getType());
1182 
1183   return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1184 }
1185 
1186 Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1187   return ::simplifySDivInst(Op0, Op1, Q, RecursionLimit);
1188 }
1189 
1190 /// Given operands for a UDiv, see if we can fold the result.
1191 /// If not, this returns null.
1192 static Value *simplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1193                                unsigned MaxRecurse) {
1194   return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1195 }
1196 
1197 Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1198   return ::simplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1199 }
1200 
1201 /// Given operands for an SRem, see if we can fold the result.
1202 /// If not, this returns null.
1203 static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1204                                unsigned MaxRecurse) {
1205   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1206   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1207   Value *X;
1208   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1209     return ConstantInt::getNullValue(Op0->getType());
1210 
1211   // If the two operands are negated, return 0.
1212   if (isKnownNegation(Op0, Op1))
1213     return ConstantInt::getNullValue(Op0->getType());
1214 
1215   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1216 }
1217 
1218 Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1219   return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
1220 }
1221 
1222 /// Given operands for a URem, see if we can fold the result.
1223 /// If not, this returns null.
1224 static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1225                                unsigned MaxRecurse) {
1226   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1227 }
1228 
1229 Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1230   return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
1231 }
1232 
1233 /// Returns true if a shift by \c Amount always yields poison.
1234 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1235   Constant *C = dyn_cast<Constant>(Amount);
1236   if (!C)
1237     return false;
1238 
1239   // X shift by undef -> poison because it may shift by the bitwidth.
1240   if (Q.isUndefValue(C))
1241     return true;
1242 
1243   // Shifting by the bitwidth or more is undefined.
1244   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1245     if (CI->getValue().uge(CI->getType()->getScalarSizeInBits()))
1246       return true;
1247 
1248   // If all lanes of a vector shift are undefined the whole shift is.
1249   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1250     for (unsigned I = 0,
1251                   E = cast<FixedVectorType>(C->getType())->getNumElements();
1252          I != E; ++I)
1253       if (!isPoisonShift(C->getAggregateElement(I), Q))
1254         return false;
1255     return true;
1256   }
1257 
1258   return false;
1259 }
1260 
1261 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1262 /// If not, this returns null.
1263 static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1264                             Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1265                             unsigned MaxRecurse) {
1266   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1267     return C;
1268 
1269   // poison shift by X -> poison
1270   if (isa<PoisonValue>(Op0))
1271     return Op0;
1272 
1273   // 0 shift by X -> 0
1274   if (match(Op0, m_Zero()))
1275     return Constant::getNullValue(Op0->getType());
1276 
1277   // X shift by 0 -> X
1278   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1279   // would be poison.
1280   Value *X;
1281   if (match(Op1, m_Zero()) ||
1282       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1283     return Op0;
1284 
1285   // Fold undefined shifts.
1286   if (isPoisonShift(Op1, Q))
1287     return PoisonValue::get(Op0->getType());
1288 
1289   // If the operation is with the result of a select instruction, check whether
1290   // operating on either branch of the select always yields the same value.
1291   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1292     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1293       return V;
1294 
1295   // If the operation is with the result of a phi instruction, check whether
1296   // operating on all incoming values of the phi always yields the same value.
1297   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1298     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1299       return V;
1300 
1301   // If any bits in the shift amount make that value greater than or equal to
1302   // the number of bits in the type, the shift is undefined.
1303   KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1304   if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1305     return PoisonValue::get(Op0->getType());
1306 
1307   // If all valid bits in the shift amount are known zero, the first operand is
1308   // unchanged.
1309   unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1310   if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1311     return Op0;
1312 
1313   // Check for nsw shl leading to a poison value.
1314   if (IsNSW) {
1315     assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1316     KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1317     KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1318 
1319     if (KnownVal.Zero.isSignBitSet())
1320       KnownShl.Zero.setSignBit();
1321     if (KnownVal.One.isSignBitSet())
1322       KnownShl.One.setSignBit();
1323 
1324     if (KnownShl.hasConflict())
1325       return PoisonValue::get(Op0->getType());
1326   }
1327 
1328   return nullptr;
1329 }
1330 
1331 /// Given operands for an Shl, LShr or AShr, see if we can
1332 /// fold the result.  If not, this returns null.
1333 static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1334                                  Value *Op1, bool isExact,
1335                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
1336   if (Value *V =
1337           simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1338     return V;
1339 
1340   // X >> X -> 0
1341   if (Op0 == Op1)
1342     return Constant::getNullValue(Op0->getType());
1343 
1344   // undef >> X -> 0
1345   // undef >> X -> undef (if it's exact)
1346   if (Q.isUndefValue(Op0))
1347     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1348 
1349   // The low bit cannot be shifted out of an exact shift if it is set.
1350   if (isExact) {
1351     KnownBits Op0Known =
1352         computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1353     if (Op0Known.One[0])
1354       return Op0;
1355   }
1356 
1357   return nullptr;
1358 }
1359 
1360 /// Given operands for an Shl, see if we can fold the result.
1361 /// If not, this returns null.
1362 static Value *simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1363                               const SimplifyQuery &Q, unsigned MaxRecurse) {
1364   if (Value *V =
1365           simplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse))
1366     return V;
1367 
1368   // undef << X -> 0
1369   // undef << X -> undef if (if it's NSW/NUW)
1370   if (Q.isUndefValue(Op0))
1371     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1372 
1373   // (X >> A) << A -> X
1374   Value *X;
1375   if (Q.IIQ.UseInstrInfo &&
1376       match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1377     return X;
1378 
1379   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1380   if (isNUW && match(Op0, m_Negative()))
1381     return Op0;
1382   // NOTE: could use computeKnownBits() / LazyValueInfo,
1383   // but the cost-benefit analysis suggests it isn't worth it.
1384 
1385   return nullptr;
1386 }
1387 
1388 Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1389                              const SimplifyQuery &Q) {
1390   return ::simplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1391 }
1392 
1393 /// Given operands for an LShr, see if we can fold the result.
1394 /// If not, this returns null.
1395 static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1396                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1397   if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1398                                     MaxRecurse))
1399     return V;
1400 
1401   // (X << A) >> A -> X
1402   Value *X;
1403   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1404     return X;
1405 
1406   // ((X << A) | Y) >> A -> X  if effective width of Y is not larger than A.
1407   // We can return X as we do in the above case since OR alters no bits in X.
1408   // SimplifyDemandedBits in InstCombine can do more general optimization for
1409   // bit manipulation. This pattern aims to provide opportunities for other
1410   // optimizers by supporting a simple but common case in InstSimplify.
1411   Value *Y;
1412   const APInt *ShRAmt, *ShLAmt;
1413   if (match(Op1, m_APInt(ShRAmt)) &&
1414       match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1415       *ShRAmt == *ShLAmt) {
1416     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1417     const unsigned EffWidthY = YKnown.countMaxActiveBits();
1418     if (ShRAmt->uge(EffWidthY))
1419       return X;
1420   }
1421 
1422   return nullptr;
1423 }
1424 
1425 Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1426                               const SimplifyQuery &Q) {
1427   return ::simplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1428 }
1429 
1430 /// Given operands for an AShr, see if we can fold the result.
1431 /// If not, this returns null.
1432 static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1433                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1434   if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1435                                     MaxRecurse))
1436     return V;
1437 
1438   // -1 >>a X --> -1
1439   // (-1 << X) a>> X --> -1
1440   // Do not return Op0 because it may contain undef elements if it's a vector.
1441   if (match(Op0, m_AllOnes()) ||
1442       match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1443     return Constant::getAllOnesValue(Op0->getType());
1444 
1445   // (X << A) >> A -> X
1446   Value *X;
1447   if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1448     return X;
1449 
1450   // Arithmetic shifting an all-sign-bit value is a no-op.
1451   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1452   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1453     return Op0;
1454 
1455   return nullptr;
1456 }
1457 
1458 Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1459                               const SimplifyQuery &Q) {
1460   return ::simplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1461 }
1462 
1463 /// Commuted variants are assumed to be handled by calling this function again
1464 /// with the parameters swapped.
1465 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1466                                          ICmpInst *UnsignedICmp, bool IsAnd,
1467                                          const SimplifyQuery &Q) {
1468   Value *X, *Y;
1469 
1470   ICmpInst::Predicate EqPred;
1471   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1472       !ICmpInst::isEquality(EqPred))
1473     return nullptr;
1474 
1475   ICmpInst::Predicate UnsignedPred;
1476 
1477   Value *A, *B;
1478   // Y = (A - B);
1479   if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1480     if (match(UnsignedICmp,
1481               m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1482         ICmpInst::isUnsigned(UnsignedPred)) {
1483       // A >=/<= B || (A - B) != 0  <-->  true
1484       if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1485            UnsignedPred == ICmpInst::ICMP_ULE) &&
1486           EqPred == ICmpInst::ICMP_NE && !IsAnd)
1487         return ConstantInt::getTrue(UnsignedICmp->getType());
1488       // A </> B && (A - B) == 0  <-->  false
1489       if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1490            UnsignedPred == ICmpInst::ICMP_UGT) &&
1491           EqPred == ICmpInst::ICMP_EQ && IsAnd)
1492         return ConstantInt::getFalse(UnsignedICmp->getType());
1493 
1494       // A </> B && (A - B) != 0  <-->  A </> B
1495       // A </> B || (A - B) != 0  <-->  (A - B) != 0
1496       if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1497                                           UnsignedPred == ICmpInst::ICMP_UGT))
1498         return IsAnd ? UnsignedICmp : ZeroICmp;
1499 
1500       // A <=/>= B && (A - B) == 0  <-->  (A - B) == 0
1501       // A <=/>= B || (A - B) == 0  <-->  A <=/>= B
1502       if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1503                                           UnsignedPred == ICmpInst::ICMP_UGE))
1504         return IsAnd ? ZeroICmp : UnsignedICmp;
1505     }
1506 
1507     // Given  Y = (A - B)
1508     //   Y >= A && Y != 0  --> Y >= A  iff B != 0
1509     //   Y <  A || Y == 0  --> Y <  A  iff B != 0
1510     if (match(UnsignedICmp,
1511               m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1512       if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1513           EqPred == ICmpInst::ICMP_NE &&
1514           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1515         return UnsignedICmp;
1516       if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1517           EqPred == ICmpInst::ICMP_EQ &&
1518           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1519         return UnsignedICmp;
1520     }
1521   }
1522 
1523   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1524       ICmpInst::isUnsigned(UnsignedPred))
1525     ;
1526   else if (match(UnsignedICmp,
1527                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1528            ICmpInst::isUnsigned(UnsignedPred))
1529     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1530   else
1531     return nullptr;
1532 
1533   // X > Y && Y == 0  -->  Y == 0  iff X != 0
1534   // X > Y || Y == 0  -->  X > Y   iff X != 0
1535   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1536       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1537     return IsAnd ? ZeroICmp : UnsignedICmp;
1538 
1539   // X <= Y && Y != 0  -->  X <= Y  iff X != 0
1540   // X <= Y || Y != 0  -->  Y != 0  iff X != 0
1541   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1542       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1543     return IsAnd ? UnsignedICmp : ZeroICmp;
1544 
1545   // The transforms below here are expected to be handled more generally with
1546   // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1547   // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1548   // these are candidates for removal.
1549 
1550   // X < Y && Y != 0  -->  X < Y
1551   // X < Y || Y != 0  -->  Y != 0
1552   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1553     return IsAnd ? UnsignedICmp : ZeroICmp;
1554 
1555   // X >= Y && Y == 0  -->  Y == 0
1556   // X >= Y || Y == 0  -->  X >= Y
1557   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1558     return IsAnd ? ZeroICmp : UnsignedICmp;
1559 
1560   // X < Y && Y == 0  -->  false
1561   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1562       IsAnd)
1563     return getFalse(UnsignedICmp->getType());
1564 
1565   // X >= Y || Y != 0  -->  true
1566   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1567       !IsAnd)
1568     return getTrue(UnsignedICmp->getType());
1569 
1570   return nullptr;
1571 }
1572 
1573 /// Commuted variants are assumed to be handled by calling this function again
1574 /// with the parameters swapped.
1575 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1576   ICmpInst::Predicate Pred0, Pred1;
1577   Value *A, *B;
1578   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1579       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1580     return nullptr;
1581 
1582   // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1583   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1584   // can eliminate Op1 from this 'and'.
1585   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1586     return Op0;
1587 
1588   // Check for any combination of predicates that are guaranteed to be disjoint.
1589   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1590       (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1591       (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1592       (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1593     return getFalse(Op0->getType());
1594 
1595   return nullptr;
1596 }
1597 
1598 /// Commuted variants are assumed to be handled by calling this function again
1599 /// with the parameters swapped.
1600 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1601   ICmpInst::Predicate Pred0, Pred1;
1602   Value *A, *B;
1603   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1604       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1605     return nullptr;
1606 
1607   // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1608   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1609   // can eliminate Op0 from this 'or'.
1610   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1611     return Op1;
1612 
1613   // Check for any combination of predicates that cover the entire range of
1614   // possibilities.
1615   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1616       (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1617       (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1618       (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1619     return getTrue(Op0->getType());
1620 
1621   return nullptr;
1622 }
1623 
1624 /// Test if a pair of compares with a shared operand and 2 constants has an
1625 /// empty set intersection, full set union, or if one compare is a superset of
1626 /// the other.
1627 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1628                                                 bool IsAnd) {
1629   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1630   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1631     return nullptr;
1632 
1633   const APInt *C0, *C1;
1634   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1635       !match(Cmp1->getOperand(1), m_APInt(C1)))
1636     return nullptr;
1637 
1638   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1639   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1640 
1641   // For and-of-compares, check if the intersection is empty:
1642   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1643   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1644     return getFalse(Cmp0->getType());
1645 
1646   // For or-of-compares, check if the union is full:
1647   // (icmp X, C0) || (icmp X, C1) --> full set --> true
1648   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1649     return getTrue(Cmp0->getType());
1650 
1651   // Is one range a superset of the other?
1652   // If this is and-of-compares, take the smaller set:
1653   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1654   // If this is or-of-compares, take the larger set:
1655   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1656   if (Range0.contains(Range1))
1657     return IsAnd ? Cmp1 : Cmp0;
1658   if (Range1.contains(Range0))
1659     return IsAnd ? Cmp0 : Cmp1;
1660 
1661   return nullptr;
1662 }
1663 
1664 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1665                                            bool IsAnd) {
1666   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1667   if (!match(Cmp0->getOperand(1), m_Zero()) ||
1668       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1669     return nullptr;
1670 
1671   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1672     return nullptr;
1673 
1674   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1675   Value *X = Cmp0->getOperand(0);
1676   Value *Y = Cmp1->getOperand(0);
1677 
1678   // If one of the compares is a masked version of a (not) null check, then
1679   // that compare implies the other, so we eliminate the other. Optionally, look
1680   // through a pointer-to-int cast to match a null check of a pointer type.
1681 
1682   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1683   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1684   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1685   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1686   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1687       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1688     return Cmp1;
1689 
1690   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1691   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1692   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1693   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1694   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1695       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1696     return Cmp0;
1697 
1698   return nullptr;
1699 }
1700 
1701 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1702                                         const InstrInfoQuery &IIQ) {
1703   // (icmp (add V, C0), C1) & (icmp V, C0)
1704   ICmpInst::Predicate Pred0, Pred1;
1705   const APInt *C0, *C1;
1706   Value *V;
1707   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1708     return nullptr;
1709 
1710   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1711     return nullptr;
1712 
1713   auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1714   if (AddInst->getOperand(1) != Op1->getOperand(1))
1715     return nullptr;
1716 
1717   Type *ITy = Op0->getType();
1718   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1719   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1720 
1721   const APInt Delta = *C1 - *C0;
1722   if (C0->isStrictlyPositive()) {
1723     if (Delta == 2) {
1724       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1725         return getFalse(ITy);
1726       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1727         return getFalse(ITy);
1728     }
1729     if (Delta == 1) {
1730       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1731         return getFalse(ITy);
1732       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1733         return getFalse(ITy);
1734     }
1735   }
1736   if (C0->getBoolValue() && isNUW) {
1737     if (Delta == 2)
1738       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1739         return getFalse(ITy);
1740     if (Delta == 1)
1741       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1742         return getFalse(ITy);
1743   }
1744 
1745   return nullptr;
1746 }
1747 
1748 /// Try to eliminate compares with signed or unsigned min/max constants.
1749 static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
1750                                                  bool IsAnd) {
1751   // Canonicalize an equality compare as Cmp0.
1752   if (Cmp1->isEquality())
1753     std::swap(Cmp0, Cmp1);
1754   if (!Cmp0->isEquality())
1755     return nullptr;
1756 
1757   // The non-equality compare must include a common operand (X). Canonicalize
1758   // the common operand as operand 0 (the predicate is swapped if the common
1759   // operand was operand 1).
1760   ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
1761   Value *X = Cmp0->getOperand(0);
1762   ICmpInst::Predicate Pred1;
1763   bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
1764   if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
1765     return nullptr;
1766   if (ICmpInst::isEquality(Pred1))
1767     return nullptr;
1768 
1769   // The equality compare must be against a constant. Flip bits if we matched
1770   // a bitwise not. Convert a null pointer constant to an integer zero value.
1771   APInt MinMaxC;
1772   const APInt *C;
1773   if (match(Cmp0->getOperand(1), m_APInt(C)))
1774     MinMaxC = HasNotOp ? ~*C : *C;
1775   else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
1776     MinMaxC = APInt::getZero(8);
1777   else
1778     return nullptr;
1779 
1780   // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
1781   if (!IsAnd) {
1782     Pred0 = ICmpInst::getInversePredicate(Pred0);
1783     Pred1 = ICmpInst::getInversePredicate(Pred1);
1784   }
1785 
1786   // Normalize to unsigned compare and unsigned min/max value.
1787   // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
1788   if (ICmpInst::isSigned(Pred1)) {
1789     Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
1790     MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
1791   }
1792 
1793   // (X != MAX) && (X < Y) --> X < Y
1794   // (X == MAX) || (X >= Y) --> X >= Y
1795   if (MinMaxC.isMaxValue())
1796     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
1797       return Cmp1;
1798 
1799   // (X != MIN) && (X > Y) -->  X > Y
1800   // (X == MIN) || (X <= Y) --> X <= Y
1801   if (MinMaxC.isMinValue())
1802     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
1803       return Cmp1;
1804 
1805   return nullptr;
1806 }
1807 
1808 /// Try to simplify and/or of icmp with ctpop intrinsic.
1809 static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1810                                             bool IsAnd) {
1811   ICmpInst::Predicate Pred0, Pred1;
1812   Value *X;
1813   const APInt *C;
1814   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1815                           m_APInt(C))) ||
1816       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1817     return nullptr;
1818 
1819   // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1820   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1821     return Cmp1;
1822   // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1823   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1824     return Cmp1;
1825 
1826   return nullptr;
1827 }
1828 
1829 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1830                                  const SimplifyQuery &Q) {
1831   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1832     return X;
1833   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1834     return X;
1835 
1836   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1837     return X;
1838   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1839     return X;
1840 
1841   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1842     return X;
1843 
1844   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1845     return X;
1846 
1847   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1848     return X;
1849 
1850   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1851     return X;
1852   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1853     return X;
1854 
1855   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1856     return X;
1857   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1858     return X;
1859 
1860   return nullptr;
1861 }
1862 
1863 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1864                                        const InstrInfoQuery &IIQ) {
1865   // (icmp (add V, C0), C1) | (icmp V, C0)
1866   ICmpInst::Predicate Pred0, Pred1;
1867   const APInt *C0, *C1;
1868   Value *V;
1869   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1870     return nullptr;
1871 
1872   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1873     return nullptr;
1874 
1875   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1876   if (AddInst->getOperand(1) != Op1->getOperand(1))
1877     return nullptr;
1878 
1879   Type *ITy = Op0->getType();
1880   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1881   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1882 
1883   const APInt Delta = *C1 - *C0;
1884   if (C0->isStrictlyPositive()) {
1885     if (Delta == 2) {
1886       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1887         return getTrue(ITy);
1888       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1889         return getTrue(ITy);
1890     }
1891     if (Delta == 1) {
1892       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1893         return getTrue(ITy);
1894       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1895         return getTrue(ITy);
1896     }
1897   }
1898   if (C0->getBoolValue() && isNUW) {
1899     if (Delta == 2)
1900       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1901         return getTrue(ITy);
1902     if (Delta == 1)
1903       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1904         return getTrue(ITy);
1905   }
1906 
1907   return nullptr;
1908 }
1909 
1910 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1911                                 const SimplifyQuery &Q) {
1912   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1913     return X;
1914   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1915     return X;
1916 
1917   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1918     return X;
1919   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1920     return X;
1921 
1922   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1923     return X;
1924 
1925   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1926     return X;
1927 
1928   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1929     return X;
1930 
1931   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1932     return X;
1933   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1934     return X;
1935 
1936   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1937     return X;
1938   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1939     return X;
1940 
1941   return nullptr;
1942 }
1943 
1944 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, FCmpInst *LHS,
1945                                    FCmpInst *RHS, bool IsAnd) {
1946   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1947   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1948   if (LHS0->getType() != RHS0->getType())
1949     return nullptr;
1950 
1951   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1952   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1953       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1954     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1955     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1956     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1957     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1958     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1959     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1960     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1961     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1962     if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1963         (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1964       return RHS;
1965 
1966     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1967     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1968     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1969     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1970     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1971     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1972     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1973     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1974     if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1975         (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1976       return LHS;
1977   }
1978 
1979   return nullptr;
1980 }
1981 
1982 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
1983                                   Value *Op1, bool IsAnd) {
1984   // Look through casts of the 'and' operands to find compares.
1985   auto *Cast0 = dyn_cast<CastInst>(Op0);
1986   auto *Cast1 = dyn_cast<CastInst>(Op1);
1987   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1988       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1989     Op0 = Cast0->getOperand(0);
1990     Op1 = Cast1->getOperand(0);
1991   }
1992 
1993   Value *V = nullptr;
1994   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1995   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1996   if (ICmp0 && ICmp1)
1997     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1998               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1999 
2000   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
2001   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
2002   if (FCmp0 && FCmp1)
2003     V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
2004 
2005   if (!V)
2006     return nullptr;
2007   if (!Cast0)
2008     return V;
2009 
2010   // If we looked through casts, we can only handle a constant simplification
2011   // because we are not allowed to create a cast instruction here.
2012   if (auto *C = dyn_cast<Constant>(V))
2013     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
2014 
2015   return nullptr;
2016 }
2017 
2018 /// Given a bitwise logic op, check if the operands are add/sub with a common
2019 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
2020 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
2021                                     Instruction::BinaryOps Opcode) {
2022   assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
2023   assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
2024   Value *X;
2025   Constant *C1, *C2;
2026   if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
2027        match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
2028       (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2029        match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2030     if (ConstantExpr::getNot(C1) == C2) {
2031       // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2032       // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2033       // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2034       Type *Ty = Op0->getType();
2035       return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2036                                         : ConstantInt::getAllOnesValue(Ty);
2037     }
2038   }
2039   return nullptr;
2040 }
2041 
2042 /// Given operands for an And, see if we can fold the result.
2043 /// If not, this returns null.
2044 static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2045                               unsigned MaxRecurse) {
2046   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2047     return C;
2048 
2049   // X & poison -> poison
2050   if (isa<PoisonValue>(Op1))
2051     return Op1;
2052 
2053   // X & undef -> 0
2054   if (Q.isUndefValue(Op1))
2055     return Constant::getNullValue(Op0->getType());
2056 
2057   // X & X = X
2058   if (Op0 == Op1)
2059     return Op0;
2060 
2061   // X & 0 = 0
2062   if (match(Op1, m_Zero()))
2063     return Constant::getNullValue(Op0->getType());
2064 
2065   // X & -1 = X
2066   if (match(Op1, m_AllOnes()))
2067     return Op0;
2068 
2069   // A & ~A  =  ~A & A  =  0
2070   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2071     return Constant::getNullValue(Op0->getType());
2072 
2073   // (A | ?) & A = A
2074   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2075     return Op1;
2076 
2077   // A & (A | ?) = A
2078   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
2079     return Op0;
2080 
2081   // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2082   Value *X, *Y;
2083   if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2084       match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2085     return X;
2086   if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2087       match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2088     return X;
2089 
2090   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2091     return V;
2092 
2093   // A mask that only clears known zeros of a shifted value is a no-op.
2094   const APInt *Mask;
2095   const APInt *ShAmt;
2096   if (match(Op1, m_APInt(Mask))) {
2097     // If all bits in the inverted and shifted mask are clear:
2098     // and (shl X, ShAmt), Mask --> shl X, ShAmt
2099     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2100         (~(*Mask)).lshr(*ShAmt).isZero())
2101       return Op0;
2102 
2103     // If all bits in the inverted and shifted mask are clear:
2104     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2105     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2106         (~(*Mask)).shl(*ShAmt).isZero())
2107       return Op0;
2108   }
2109 
2110   // If we have a multiplication overflow check that is being 'and'ed with a
2111   // check that one of the multipliers is not zero, we can omit the 'and', and
2112   // only keep the overflow check.
2113   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2114     return Op1;
2115   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
2116     return Op0;
2117 
2118   // A & (-A) = A if A is a power of two or zero.
2119   if (match(Op0, m_Neg(m_Specific(Op1))) ||
2120       match(Op1, m_Neg(m_Specific(Op0)))) {
2121     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2122                                Q.DT))
2123       return Op0;
2124     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2125                                Q.DT))
2126       return Op1;
2127   }
2128 
2129   // This is a similar pattern used for checking if a value is a power-of-2:
2130   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2131   // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
2132   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2133       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2134     return Constant::getNullValue(Op1->getType());
2135   if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
2136       isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2137     return Constant::getNullValue(Op0->getType());
2138 
2139   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2140     return V;
2141 
2142   // Try some generic simplifications for associative operations.
2143   if (Value *V =
2144           simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
2145     return V;
2146 
2147   // And distributes over Or.  Try some generic simplifications based on this.
2148   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2149                                         Instruction::Or, Q, MaxRecurse))
2150     return V;
2151 
2152   // And distributes over Xor.  Try some generic simplifications based on this.
2153   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2154                                         Instruction::Xor, Q, MaxRecurse))
2155     return V;
2156 
2157   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2158     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2159       // A & (A && B) -> A && B
2160       if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2161         return Op1;
2162       else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2163         return Op0;
2164     }
2165     // If the operation is with the result of a select instruction, check
2166     // whether operating on either branch of the select always yields the same
2167     // value.
2168     if (Value *V =
2169             threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
2170       return V;
2171   }
2172 
2173   // If the operation is with the result of a phi instruction, check whether
2174   // operating on all incoming values of the phi always yields the same value.
2175   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2176     if (Value *V =
2177             threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
2178       return V;
2179 
2180   // Assuming the effective width of Y is not larger than A, i.e. all bits
2181   // from X and Y are disjoint in (X << A) | Y,
2182   // if the mask of this AND op covers all bits of X or Y, while it covers
2183   // no bits from the other, we can bypass this AND op. E.g.,
2184   // ((X << A) | Y) & Mask -> Y,
2185   //     if Mask = ((1 << effective_width_of(Y)) - 1)
2186   // ((X << A) | Y) & Mask -> X << A,
2187   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
2188   // SimplifyDemandedBits in InstCombine can optimize the general case.
2189   // This pattern aims to help other passes for a common case.
2190   Value *XShifted;
2191   if (match(Op1, m_APInt(Mask)) &&
2192       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2193                                      m_Value(XShifted)),
2194                         m_Value(Y)))) {
2195     const unsigned Width = Op0->getType()->getScalarSizeInBits();
2196     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2197     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2198     const unsigned EffWidthY = YKnown.countMaxActiveBits();
2199     if (EffWidthY <= ShftCnt) {
2200       const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2201       const unsigned EffWidthX = XKnown.countMaxActiveBits();
2202       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2203       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2204       // If the mask is extracting all bits from X or Y as is, we can skip
2205       // this AND op.
2206       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2207         return Y;
2208       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2209         return XShifted;
2210     }
2211   }
2212 
2213   // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2214   // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2215   BinaryOperator *Or;
2216   if (match(Op0, m_c_Xor(m_Value(X),
2217                          m_CombineAnd(m_BinOp(Or),
2218                                       m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2219       match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2220     return Constant::getNullValue(Op0->getType());
2221 
2222   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2223     // Op0&Op1 -> Op0 where Op0 implies Op1
2224     if (isImpliedCondition(Op0, Op1, Q.DL).value_or(false))
2225       return Op0;
2226     // Op0&Op1 -> Op1 where Op1 implies Op0
2227     if (isImpliedCondition(Op1, Op0, Q.DL).value_or(false))
2228       return Op1;
2229   }
2230 
2231   return nullptr;
2232 }
2233 
2234 Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2235   return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
2236 }
2237 
2238 static Value *simplifyOrLogic(Value *X, Value *Y) {
2239   assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2240   Type *Ty = X->getType();
2241 
2242   // X | ~X --> -1
2243   if (match(Y, m_Not(m_Specific(X))))
2244     return ConstantInt::getAllOnesValue(Ty);
2245 
2246   // X | ~(X & ?) = -1
2247   if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2248     return ConstantInt::getAllOnesValue(Ty);
2249 
2250   // X | (X & ?) --> X
2251   if (match(Y, m_c_And(m_Specific(X), m_Value())))
2252     return X;
2253 
2254   Value *A, *B;
2255 
2256   // (A ^ B) | (A | B) --> A | B
2257   // (A ^ B) | (B | A) --> B | A
2258   if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2259       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2260     return Y;
2261 
2262   // ~(A ^ B) | (A | B) --> -1
2263   // ~(A ^ B) | (B | A) --> -1
2264   if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2265       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2266     return ConstantInt::getAllOnesValue(Ty);
2267 
2268   // (A & ~B) | (A ^ B) --> A ^ B
2269   // (~B & A) | (A ^ B) --> A ^ B
2270   // (A & ~B) | (B ^ A) --> B ^ A
2271   // (~B & A) | (B ^ A) --> B ^ A
2272   if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2273       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2274     return Y;
2275 
2276   // (~A ^ B) | (A & B) --> ~A ^ B
2277   // (B ^ ~A) | (A & B) --> B ^ ~A
2278   // (~A ^ B) | (B & A) --> ~A ^ B
2279   // (B ^ ~A) | (B & A) --> B ^ ~A
2280   if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2281       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2282     return X;
2283 
2284   // (~A | B) | (A ^ B) --> -1
2285   // (~A | B) | (B ^ A) --> -1
2286   // (B | ~A) | (A ^ B) --> -1
2287   // (B | ~A) | (B ^ A) --> -1
2288   if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2289       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2290     return ConstantInt::getAllOnesValue(Ty);
2291 
2292   // (~A & B) | ~(A | B) --> ~A
2293   // (~A & B) | ~(B | A) --> ~A
2294   // (B & ~A) | ~(A | B) --> ~A
2295   // (B & ~A) | ~(B | A) --> ~A
2296   Value *NotA;
2297   if (match(X,
2298             m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2299                     m_Value(B))) &&
2300       match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2301     return NotA;
2302 
2303   // ~(A ^ B) | (A & B) --> ~(A ^ B)
2304   // ~(A ^ B) | (B & A) --> ~(A ^ B)
2305   Value *NotAB;
2306   if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
2307                             m_Value(NotAB))) &&
2308       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2309     return NotAB;
2310 
2311   // ~(A & B) | (A ^ B) --> ~(A & B)
2312   // ~(A & B) | (B ^ A) --> ~(A & B)
2313   if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
2314                             m_Value(NotAB))) &&
2315       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2316     return NotAB;
2317 
2318   return nullptr;
2319 }
2320 
2321 /// Given operands for an Or, see if we can fold the result.
2322 /// If not, this returns null.
2323 static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2324                              unsigned MaxRecurse) {
2325   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2326     return C;
2327 
2328   // X | poison -> poison
2329   if (isa<PoisonValue>(Op1))
2330     return Op1;
2331 
2332   // X | undef -> -1
2333   // X | -1 = -1
2334   // Do not return Op1 because it may contain undef elements if it's a vector.
2335   if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2336     return Constant::getAllOnesValue(Op0->getType());
2337 
2338   // X | X = X
2339   // X | 0 = X
2340   if (Op0 == Op1 || match(Op1, m_Zero()))
2341     return Op0;
2342 
2343   if (Value *R = simplifyOrLogic(Op0, Op1))
2344     return R;
2345   if (Value *R = simplifyOrLogic(Op1, Op0))
2346     return R;
2347 
2348   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2349     return V;
2350 
2351   // Rotated -1 is still -1:
2352   // (-1 << X) | (-1 >> (C - X)) --> -1
2353   // (-1 >> X) | (-1 << (C - X)) --> -1
2354   // ...with C <= bitwidth (and commuted variants).
2355   Value *X, *Y;
2356   if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2357        match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2358       (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2359        match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2360     const APInt *C;
2361     if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2362          match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2363         C->ule(X->getType()->getScalarSizeInBits())) {
2364       return ConstantInt::getAllOnesValue(X->getType());
2365     }
2366   }
2367 
2368   // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2369   // are mixing in another shift that is redundant with the funnel shift.
2370 
2371   // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2372   // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2373   if (match(Op0,
2374             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2375       match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2376     return Op0;
2377   if (match(Op1,
2378             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2379       match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2380     return Op1;
2381 
2382   // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2383   // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2384   if (match(Op0,
2385             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2386       match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2387     return Op0;
2388   if (match(Op1,
2389             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2390       match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2391     return Op1;
2392 
2393   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2394     return V;
2395 
2396   // If we have a multiplication overflow check that is being 'and'ed with a
2397   // check that one of the multipliers is not zero, we can omit the 'and', and
2398   // only keep the overflow check.
2399   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2400     return Op1;
2401   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2402     return Op0;
2403 
2404   // Try some generic simplifications for associative operations.
2405   if (Value *V =
2406           simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2407     return V;
2408 
2409   // Or distributes over And.  Try some generic simplifications based on this.
2410   if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2411                                         Instruction::And, Q, MaxRecurse))
2412     return V;
2413 
2414   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2415     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2416       // A | (A || B) -> A || B
2417       if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2418         return Op1;
2419       else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2420         return Op0;
2421     }
2422     // If the operation is with the result of a select instruction, check
2423     // whether operating on either branch of the select always yields the same
2424     // value.
2425     if (Value *V =
2426             threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2427       return V;
2428   }
2429 
2430   // (A & C1)|(B & C2)
2431   Value *A, *B;
2432   const APInt *C1, *C2;
2433   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2434       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2435     if (*C1 == ~*C2) {
2436       // (A & C1)|(B & C2)
2437       // If we have: ((V + N) & C1) | (V & C2)
2438       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2439       // replace with V+N.
2440       Value *N;
2441       if (C2->isMask() && // C2 == 0+1+
2442           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2443         // Add commutes, try both ways.
2444         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2445           return A;
2446       }
2447       // Or commutes, try both ways.
2448       if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2449         // Add commutes, try both ways.
2450         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2451           return B;
2452       }
2453     }
2454   }
2455 
2456   // If the operation is with the result of a phi instruction, check whether
2457   // operating on all incoming values of the phi always yields the same value.
2458   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2459     if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2460       return V;
2461 
2462   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2463     // Op0|Op1 -> Op1 where Op0 implies Op1
2464     if (isImpliedCondition(Op0, Op1, Q.DL).value_or(false))
2465       return Op1;
2466     // Op0|Op1 -> Op0 where Op1 implies Op0
2467     if (isImpliedCondition(Op1, Op0, Q.DL).value_or(false))
2468       return Op0;
2469   }
2470 
2471   return nullptr;
2472 }
2473 
2474 Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2475   return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
2476 }
2477 
2478 /// Given operands for a Xor, see if we can fold the result.
2479 /// If not, this returns null.
2480 static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2481                               unsigned MaxRecurse) {
2482   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2483     return C;
2484 
2485   // X ^ poison -> poison
2486   if (isa<PoisonValue>(Op1))
2487     return Op1;
2488 
2489   // A ^ undef -> undef
2490   if (Q.isUndefValue(Op1))
2491     return Op1;
2492 
2493   // A ^ 0 = A
2494   if (match(Op1, m_Zero()))
2495     return Op0;
2496 
2497   // A ^ A = 0
2498   if (Op0 == Op1)
2499     return Constant::getNullValue(Op0->getType());
2500 
2501   // A ^ ~A  =  ~A ^ A  =  -1
2502   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2503     return Constant::getAllOnesValue(Op0->getType());
2504 
2505   auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2506     Value *A, *B;
2507     // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2508     if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2509         match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2510       return A;
2511 
2512     // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2513     // The 'not' op must contain a complete -1 operand (no undef elements for
2514     // vector) for the transform to be safe.
2515     Value *NotA;
2516     if (match(X,
2517               m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
2518                      m_Value(B))) &&
2519         match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2520       return NotA;
2521 
2522     return nullptr;
2523   };
2524   if (Value *R = foldAndOrNot(Op0, Op1))
2525     return R;
2526   if (Value *R = foldAndOrNot(Op1, Op0))
2527     return R;
2528 
2529   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2530     return V;
2531 
2532   // Try some generic simplifications for associative operations.
2533   if (Value *V =
2534           simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2535     return V;
2536 
2537   // Threading Xor over selects and phi nodes is pointless, so don't bother.
2538   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2539   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2540   // only if B and C are equal.  If B and C are equal then (since we assume
2541   // that operands have already been simplified) "select(cond, B, C)" should
2542   // have been simplified to the common value of B and C already.  Analysing
2543   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
2544   // for threading over phi nodes.
2545 
2546   return nullptr;
2547 }
2548 
2549 Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2550   return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
2551 }
2552 
2553 static Type *getCompareTy(Value *Op) {
2554   return CmpInst::makeCmpResultType(Op->getType());
2555 }
2556 
2557 /// Rummage around inside V looking for something equivalent to the comparison
2558 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2559 /// Helper function for analyzing max/min idioms.
2560 static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2561                                          Value *LHS, Value *RHS) {
2562   SelectInst *SI = dyn_cast<SelectInst>(V);
2563   if (!SI)
2564     return nullptr;
2565   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2566   if (!Cmp)
2567     return nullptr;
2568   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2569   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2570     return Cmp;
2571   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2572       LHS == CmpRHS && RHS == CmpLHS)
2573     return Cmp;
2574   return nullptr;
2575 }
2576 
2577 /// Return true if the underlying object (storage) must be disjoint from
2578 /// storage returned by any noalias return call.
2579 static bool isAllocDisjoint(const Value *V) {
2580   // For allocas, we consider only static ones (dynamic
2581   // allocas might be transformed into calls to malloc not simultaneously
2582   // live with the compared-to allocation). For globals, we exclude symbols
2583   // that might be resolve lazily to symbols in another dynamically-loaded
2584   // library (and, thus, could be malloc'ed by the implementation).
2585   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2586     return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2587   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2588     return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2589             GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2590            !GV->isThreadLocal();
2591   if (const Argument *A = dyn_cast<Argument>(V))
2592     return A->hasByValAttr();
2593   return false;
2594 }
2595 
2596 /// Return true if V1 and V2 are each the base of some distict storage region
2597 /// [V, object_size(V)] which do not overlap.  Note that zero sized regions
2598 /// *are* possible, and that zero sized regions do not overlap with any other.
2599 static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2600   // Global variables always exist, so they always exist during the lifetime
2601   // of each other and all allocas.  Global variables themselves usually have
2602   // non-overlapping storage, but since their addresses are constants, the
2603   // case involving two globals does not reach here and is instead handled in
2604   // constant folding.
2605   //
2606   // Two different allocas usually have different addresses...
2607   //
2608   // However, if there's an @llvm.stackrestore dynamically in between two
2609   // allocas, they may have the same address. It's tempting to reduce the
2610   // scope of the problem by only looking at *static* allocas here. That would
2611   // cover the majority of allocas while significantly reducing the likelihood
2612   // of having an @llvm.stackrestore pop up in the middle. However, it's not
2613   // actually impossible for an @llvm.stackrestore to pop up in the middle of
2614   // an entry block. Also, if we have a block that's not attached to a
2615   // function, we can't tell if it's "static" under the current definition.
2616   // Theoretically, this problem could be fixed by creating a new kind of
2617   // instruction kind specifically for static allocas. Such a new instruction
2618   // could be required to be at the top of the entry block, thus preventing it
2619   // from being subject to a @llvm.stackrestore. Instcombine could even
2620   // convert regular allocas into these special allocas. It'd be nifty.
2621   // However, until then, this problem remains open.
2622   //
2623   // So, we'll assume that two non-empty allocas have different addresses
2624   // for now.
2625   auto isByValArg = [](const Value *V) {
2626     const Argument *A = dyn_cast<Argument>(V);
2627     return A && A->hasByValAttr();
2628   };
2629 
2630   // Byval args are backed by store which does not overlap with each other,
2631   // allocas, or globals.
2632   if (isByValArg(V1))
2633     return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2634   if (isByValArg(V2))
2635     return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2636 
2637   return isa<AllocaInst>(V1) &&
2638          (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2639 }
2640 
2641 // A significant optimization not implemented here is assuming that alloca
2642 // addresses are not equal to incoming argument values. They don't *alias*,
2643 // as we say, but that doesn't mean they aren't equal, so we take a
2644 // conservative approach.
2645 //
2646 // This is inspired in part by C++11 5.10p1:
2647 //   "Two pointers of the same type compare equal if and only if they are both
2648 //    null, both point to the same function, or both represent the same
2649 //    address."
2650 //
2651 // This is pretty permissive.
2652 //
2653 // It's also partly due to C11 6.5.9p6:
2654 //   "Two pointers compare equal if and only if both are null pointers, both are
2655 //    pointers to the same object (including a pointer to an object and a
2656 //    subobject at its beginning) or function, both are pointers to one past the
2657 //    last element of the same array object, or one is a pointer to one past the
2658 //    end of one array object and the other is a pointer to the start of a
2659 //    different array object that happens to immediately follow the first array
2660 //    object in the address space.)
2661 //
2662 // C11's version is more restrictive, however there's no reason why an argument
2663 // couldn't be a one-past-the-end value for a stack object in the caller and be
2664 // equal to the beginning of a stack object in the callee.
2665 //
2666 // If the C and C++ standards are ever made sufficiently restrictive in this
2667 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2668 // this optimization.
2669 static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
2670                                     Value *RHS, const SimplifyQuery &Q) {
2671   const DataLayout &DL = Q.DL;
2672   const TargetLibraryInfo *TLI = Q.TLI;
2673   const DominatorTree *DT = Q.DT;
2674   const Instruction *CxtI = Q.CxtI;
2675   const InstrInfoQuery &IIQ = Q.IIQ;
2676 
2677   // First, skip past any trivial no-ops.
2678   LHS = LHS->stripPointerCasts();
2679   RHS = RHS->stripPointerCasts();
2680 
2681   // A non-null pointer is not equal to a null pointer.
2682   if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2683       llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2684                            IIQ.UseInstrInfo))
2685     return ConstantInt::get(getCompareTy(LHS), !CmpInst::isTrueWhenEqual(Pred));
2686 
2687   // We can only fold certain predicates on pointer comparisons.
2688   switch (Pred) {
2689   default:
2690     return nullptr;
2691 
2692     // Equality comaprisons are easy to fold.
2693   case CmpInst::ICMP_EQ:
2694   case CmpInst::ICMP_NE:
2695     break;
2696 
2697     // We can only handle unsigned relational comparisons because 'inbounds' on
2698     // a GEP only protects against unsigned wrapping.
2699   case CmpInst::ICMP_UGT:
2700   case CmpInst::ICMP_UGE:
2701   case CmpInst::ICMP_ULT:
2702   case CmpInst::ICMP_ULE:
2703     // However, we have to switch them to their signed variants to handle
2704     // negative indices from the base pointer.
2705     Pred = ICmpInst::getSignedPredicate(Pred);
2706     break;
2707   }
2708 
2709   // Strip off any constant offsets so that we can reason about them.
2710   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2711   // here and compare base addresses like AliasAnalysis does, however there are
2712   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2713   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2714   // doesn't need to guarantee pointer inequality when it says NoAlias.
2715 
2716   // Even if an non-inbounds GEP occurs along the path we can still optimize
2717   // equality comparisons concerning the result.
2718   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2719   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2720   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
2721 
2722   // If LHS and RHS are related via constant offsets to the same base
2723   // value, we can replace it with an icmp which just compares the offsets.
2724   if (LHS == RHS)
2725     return ConstantInt::get(getCompareTy(LHS),
2726                             ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2727 
2728   // Various optimizations for (in)equality comparisons.
2729   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2730     // Different non-empty allocations that exist at the same time have
2731     // different addresses (if the program can tell). If the offsets are
2732     // within the bounds of their allocations (and not one-past-the-end!
2733     // so we can't use inbounds!), and their allocations aren't the same,
2734     // the pointers are not equal.
2735     if (haveNonOverlappingStorage(LHS, RHS)) {
2736       uint64_t LHSSize, RHSSize;
2737       ObjectSizeOpts Opts;
2738       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2739       auto *F = [](Value *V) -> Function * {
2740         if (auto *I = dyn_cast<Instruction>(V))
2741           return I->getFunction();
2742         if (auto *A = dyn_cast<Argument>(V))
2743           return A->getParent();
2744         return nullptr;
2745       }(LHS);
2746       Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2747       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2748           getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2749           !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2750           LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2751         return ConstantInt::get(getCompareTy(LHS),
2752                                 !CmpInst::isTrueWhenEqual(Pred));
2753       }
2754     }
2755 
2756     // If one side of the equality comparison must come from a noalias call
2757     // (meaning a system memory allocation function), and the other side must
2758     // come from a pointer that cannot overlap with dynamically-allocated
2759     // memory within the lifetime of the current function (allocas, byval
2760     // arguments, globals), then determine the comparison result here.
2761     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2762     getUnderlyingObjects(LHS, LHSUObjs);
2763     getUnderlyingObjects(RHS, RHSUObjs);
2764 
2765     // Is the set of underlying objects all noalias calls?
2766     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2767       return all_of(Objects, isNoAliasCall);
2768     };
2769 
2770     // Is the set of underlying objects all things which must be disjoint from
2771     // noalias calls.  We assume that indexing from such disjoint storage
2772     // into the heap is undefined, and thus offsets can be safely ignored.
2773     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2774       return all_of(Objects, ::isAllocDisjoint);
2775     };
2776 
2777     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2778         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2779       return ConstantInt::get(getCompareTy(LHS),
2780                               !CmpInst::isTrueWhenEqual(Pred));
2781 
2782     // Fold comparisons for non-escaping pointer even if the allocation call
2783     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2784     // dynamic allocation call could be either of the operands.  Note that
2785     // the other operand can not be based on the alloc - if it were, then
2786     // the cmp itself would be a capture.
2787     Value *MI = nullptr;
2788     if (isAllocLikeFn(LHS, TLI) &&
2789         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2790       MI = LHS;
2791     else if (isAllocLikeFn(RHS, TLI) &&
2792              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2793       MI = RHS;
2794     // FIXME: We should also fold the compare when the pointer escapes, but the
2795     // compare dominates the pointer escape
2796     if (MI && !PointerMayBeCaptured(MI, true, true))
2797       return ConstantInt::get(getCompareTy(LHS),
2798                               CmpInst::isFalseWhenEqual(Pred));
2799   }
2800 
2801   // Otherwise, fail.
2802   return nullptr;
2803 }
2804 
2805 /// Fold an icmp when its operands have i1 scalar type.
2806 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2807                                   Value *RHS, const SimplifyQuery &Q) {
2808   Type *ITy = getCompareTy(LHS); // The return type.
2809   Type *OpTy = LHS->getType();   // The operand type.
2810   if (!OpTy->isIntOrIntVectorTy(1))
2811     return nullptr;
2812 
2813   // A boolean compared to true/false can be reduced in 14 out of the 20
2814   // (10 predicates * 2 constants) possible combinations. The other
2815   // 6 cases require a 'not' of the LHS.
2816 
2817   auto ExtractNotLHS = [](Value *V) -> Value * {
2818     Value *X;
2819     if (match(V, m_Not(m_Value(X))))
2820       return X;
2821     return nullptr;
2822   };
2823 
2824   if (match(RHS, m_Zero())) {
2825     switch (Pred) {
2826     case CmpInst::ICMP_NE:  // X !=  0 -> X
2827     case CmpInst::ICMP_UGT: // X >u  0 -> X
2828     case CmpInst::ICMP_SLT: // X <s  0 -> X
2829       return LHS;
2830 
2831     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2832     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2833     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2834       if (Value *X = ExtractNotLHS(LHS))
2835         return X;
2836       break;
2837 
2838     case CmpInst::ICMP_ULT: // X <u  0 -> false
2839     case CmpInst::ICMP_SGT: // X >s  0 -> false
2840       return getFalse(ITy);
2841 
2842     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2843     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2844       return getTrue(ITy);
2845 
2846     default:
2847       break;
2848     }
2849   } else if (match(RHS, m_One())) {
2850     switch (Pred) {
2851     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2852     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2853     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2854       return LHS;
2855 
2856     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2857     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2858     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2859       if (Value *X = ExtractNotLHS(LHS))
2860         return X;
2861       break;
2862 
2863     case CmpInst::ICMP_UGT: // X >u   1 -> false
2864     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2865       return getFalse(ITy);
2866 
2867     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2868     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2869       return getTrue(ITy);
2870 
2871     default:
2872       break;
2873     }
2874   }
2875 
2876   switch (Pred) {
2877   default:
2878     break;
2879   case ICmpInst::ICMP_UGE:
2880     if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2881       return getTrue(ITy);
2882     break;
2883   case ICmpInst::ICMP_SGE:
2884     /// For signed comparison, the values for an i1 are 0 and -1
2885     /// respectively. This maps into a truth table of:
2886     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2887     ///  0  |  0  |  1 (0 >= 0)   |  1
2888     ///  0  |  1  |  1 (0 >= -1)  |  1
2889     ///  1  |  0  |  0 (-1 >= 0)  |  0
2890     ///  1  |  1  |  1 (-1 >= -1) |  1
2891     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2892       return getTrue(ITy);
2893     break;
2894   case ICmpInst::ICMP_ULE:
2895     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2896       return getTrue(ITy);
2897     break;
2898   }
2899 
2900   return nullptr;
2901 }
2902 
2903 /// Try hard to fold icmp with zero RHS because this is a common case.
2904 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2905                                    Value *RHS, const SimplifyQuery &Q) {
2906   if (!match(RHS, m_Zero()))
2907     return nullptr;
2908 
2909   Type *ITy = getCompareTy(LHS); // The return type.
2910   switch (Pred) {
2911   default:
2912     llvm_unreachable("Unknown ICmp predicate!");
2913   case ICmpInst::ICMP_ULT:
2914     return getFalse(ITy);
2915   case ICmpInst::ICMP_UGE:
2916     return getTrue(ITy);
2917   case ICmpInst::ICMP_EQ:
2918   case ICmpInst::ICMP_ULE:
2919     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2920       return getFalse(ITy);
2921     break;
2922   case ICmpInst::ICMP_NE:
2923   case ICmpInst::ICMP_UGT:
2924     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2925       return getTrue(ITy);
2926     break;
2927   case ICmpInst::ICMP_SLT: {
2928     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2929     if (LHSKnown.isNegative())
2930       return getTrue(ITy);
2931     if (LHSKnown.isNonNegative())
2932       return getFalse(ITy);
2933     break;
2934   }
2935   case ICmpInst::ICMP_SLE: {
2936     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2937     if (LHSKnown.isNegative())
2938       return getTrue(ITy);
2939     if (LHSKnown.isNonNegative() &&
2940         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2941       return getFalse(ITy);
2942     break;
2943   }
2944   case ICmpInst::ICMP_SGE: {
2945     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2946     if (LHSKnown.isNegative())
2947       return getFalse(ITy);
2948     if (LHSKnown.isNonNegative())
2949       return getTrue(ITy);
2950     break;
2951   }
2952   case ICmpInst::ICMP_SGT: {
2953     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2954     if (LHSKnown.isNegative())
2955       return getFalse(ITy);
2956     if (LHSKnown.isNonNegative() &&
2957         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2958       return getTrue(ITy);
2959     break;
2960   }
2961   }
2962 
2963   return nullptr;
2964 }
2965 
2966 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2967                                        Value *RHS, const InstrInfoQuery &IIQ) {
2968   Type *ITy = getCompareTy(RHS); // The return type.
2969 
2970   Value *X;
2971   // Sign-bit checks can be optimized to true/false after unsigned
2972   // floating-point casts:
2973   // icmp slt (bitcast (uitofp X)),  0 --> false
2974   // icmp sgt (bitcast (uitofp X)), -1 --> true
2975   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2976     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2977       return ConstantInt::getFalse(ITy);
2978     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2979       return ConstantInt::getTrue(ITy);
2980   }
2981 
2982   const APInt *C;
2983   if (!match(RHS, m_APIntAllowUndef(C)))
2984     return nullptr;
2985 
2986   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2987   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2988   if (RHS_CR.isEmptySet())
2989     return ConstantInt::getFalse(ITy);
2990   if (RHS_CR.isFullSet())
2991     return ConstantInt::getTrue(ITy);
2992 
2993   ConstantRange LHS_CR =
2994       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
2995   if (!LHS_CR.isFullSet()) {
2996     if (RHS_CR.contains(LHS_CR))
2997       return ConstantInt::getTrue(ITy);
2998     if (RHS_CR.inverse().contains(LHS_CR))
2999       return ConstantInt::getFalse(ITy);
3000   }
3001 
3002   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
3003   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3004   const APInt *MulC;
3005   if (ICmpInst::isEquality(Pred) &&
3006       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3007         *MulC != 0 && C->urem(*MulC) != 0) ||
3008        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3009         *MulC != 0 && C->srem(*MulC) != 0)))
3010     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
3011 
3012   return nullptr;
3013 }
3014 
3015 static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
3016                                          BinaryOperator *LBO, Value *RHS,
3017                                          const SimplifyQuery &Q,
3018                                          unsigned MaxRecurse) {
3019   Type *ITy = getCompareTy(RHS); // The return type.
3020 
3021   Value *Y = nullptr;
3022   // icmp pred (or X, Y), X
3023   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3024     if (Pred == ICmpInst::ICMP_ULT)
3025       return getFalse(ITy);
3026     if (Pred == ICmpInst::ICMP_UGE)
3027       return getTrue(ITy);
3028 
3029     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3030       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3031       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3032       if (RHSKnown.isNonNegative() && YKnown.isNegative())
3033         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3034       if (RHSKnown.isNegative() || YKnown.isNonNegative())
3035         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3036     }
3037   }
3038 
3039   // icmp pred (and X, Y), X
3040   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
3041     if (Pred == ICmpInst::ICMP_UGT)
3042       return getFalse(ITy);
3043     if (Pred == ICmpInst::ICMP_ULE)
3044       return getTrue(ITy);
3045   }
3046 
3047   // icmp pred (urem X, Y), Y
3048   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3049     switch (Pred) {
3050     default:
3051       break;
3052     case ICmpInst::ICMP_SGT:
3053     case ICmpInst::ICMP_SGE: {
3054       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3055       if (!Known.isNonNegative())
3056         break;
3057       LLVM_FALLTHROUGH;
3058     }
3059     case ICmpInst::ICMP_EQ:
3060     case ICmpInst::ICMP_UGT:
3061     case ICmpInst::ICMP_UGE:
3062       return getFalse(ITy);
3063     case ICmpInst::ICMP_SLT:
3064     case ICmpInst::ICMP_SLE: {
3065       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3066       if (!Known.isNonNegative())
3067         break;
3068       LLVM_FALLTHROUGH;
3069     }
3070     case ICmpInst::ICMP_NE:
3071     case ICmpInst::ICMP_ULT:
3072     case ICmpInst::ICMP_ULE:
3073       return getTrue(ITy);
3074     }
3075   }
3076 
3077   // icmp pred (urem X, Y), X
3078   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3079     if (Pred == ICmpInst::ICMP_ULE)
3080       return getTrue(ITy);
3081     if (Pred == ICmpInst::ICMP_UGT)
3082       return getFalse(ITy);
3083   }
3084 
3085   // x >>u y <=u x --> true.
3086   // x >>u y >u  x --> false.
3087   // x udiv y <=u x --> true.
3088   // x udiv y >u  x --> false.
3089   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3090       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3091     // icmp pred (X op Y), X
3092     if (Pred == ICmpInst::ICMP_UGT)
3093       return getFalse(ITy);
3094     if (Pred == ICmpInst::ICMP_ULE)
3095       return getTrue(ITy);
3096   }
3097 
3098   // If x is nonzero:
3099   // x >>u C <u  x --> true  for C != 0.
3100   // x >>u C !=  x --> true  for C != 0.
3101   // x >>u C >=u x --> false for C != 0.
3102   // x >>u C ==  x --> false for C != 0.
3103   // x udiv C <u  x --> true  for C != 1.
3104   // x udiv C !=  x --> true  for C != 1.
3105   // x udiv C >=u x --> false for C != 1.
3106   // x udiv C ==  x --> false for C != 1.
3107   // TODO: allow non-constant shift amount/divisor
3108   const APInt *C;
3109   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3110       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3111     if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3112       switch (Pred) {
3113       default:
3114         break;
3115       case ICmpInst::ICMP_EQ:
3116       case ICmpInst::ICMP_UGE:
3117         return getFalse(ITy);
3118       case ICmpInst::ICMP_NE:
3119       case ICmpInst::ICMP_ULT:
3120         return getTrue(ITy);
3121       case ICmpInst::ICMP_UGT:
3122       case ICmpInst::ICMP_ULE:
3123         // UGT/ULE are handled by the more general case just above
3124         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3125       }
3126     }
3127   }
3128 
3129   // (x*C1)/C2 <= x for C1 <= C2.
3130   // This holds even if the multiplication overflows: Assume that x != 0 and
3131   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3132   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3133   //
3134   // Additionally, either the multiplication and division might be represented
3135   // as shifts:
3136   // (x*C1)>>C2 <= x for C1 < 2**C2.
3137   // (x<<C1)/C2 <= x for 2**C1 < C2.
3138   const APInt *C1, *C2;
3139   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3140        C1->ule(*C2)) ||
3141       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3142        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3143       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3144        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3145     if (Pred == ICmpInst::ICMP_UGT)
3146       return getFalse(ITy);
3147     if (Pred == ICmpInst::ICMP_ULE)
3148       return getTrue(ITy);
3149   }
3150 
3151   return nullptr;
3152 }
3153 
3154 // If only one of the icmp's operands has NSW flags, try to prove that:
3155 //
3156 //   icmp slt (x + C1), (x +nsw C2)
3157 //
3158 // is equivalent to:
3159 //
3160 //   icmp slt C1, C2
3161 //
3162 // which is true if x + C2 has the NSW flags set and:
3163 // *) C1 < C2 && C1 >= 0, or
3164 // *) C2 < C1 && C1 <= 0.
3165 //
3166 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3167                                     Value *RHS) {
3168   // TODO: only support icmp slt for now.
3169   if (Pred != CmpInst::ICMP_SLT)
3170     return false;
3171 
3172   // Canonicalize nsw add as RHS.
3173   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3174     std::swap(LHS, RHS);
3175   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3176     return false;
3177 
3178   Value *X;
3179   const APInt *C1, *C2;
3180   if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3181       !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3182     return false;
3183 
3184   return (C1->slt(*C2) && C1->isNonNegative()) ||
3185          (C2->slt(*C1) && C1->isNonPositive());
3186 }
3187 
3188 /// TODO: A large part of this logic is duplicated in InstCombine's
3189 /// foldICmpBinOp(). We should be able to share that and avoid the code
3190 /// duplication.
3191 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3192                                     Value *RHS, const SimplifyQuery &Q,
3193                                     unsigned MaxRecurse) {
3194   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3195   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3196   if (MaxRecurse && (LBO || RBO)) {
3197     // Analyze the case when either LHS or RHS is an add instruction.
3198     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3199     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3200     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3201     if (LBO && LBO->getOpcode() == Instruction::Add) {
3202       A = LBO->getOperand(0);
3203       B = LBO->getOperand(1);
3204       NoLHSWrapProblem =
3205           ICmpInst::isEquality(Pred) ||
3206           (CmpInst::isUnsigned(Pred) &&
3207            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3208           (CmpInst::isSigned(Pred) &&
3209            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3210     }
3211     if (RBO && RBO->getOpcode() == Instruction::Add) {
3212       C = RBO->getOperand(0);
3213       D = RBO->getOperand(1);
3214       NoRHSWrapProblem =
3215           ICmpInst::isEquality(Pred) ||
3216           (CmpInst::isUnsigned(Pred) &&
3217            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3218           (CmpInst::isSigned(Pred) &&
3219            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3220     }
3221 
3222     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3223     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3224       if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
3225                                       Constant::getNullValue(RHS->getType()), Q,
3226                                       MaxRecurse - 1))
3227         return V;
3228 
3229     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3230     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3231       if (Value *V =
3232               simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3233                                C == LHS ? D : C, Q, MaxRecurse - 1))
3234         return V;
3235 
3236     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3237     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3238                        trySimplifyICmpWithAdds(Pred, LHS, RHS);
3239     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3240       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3241       Value *Y, *Z;
3242       if (A == C) {
3243         // C + B == C + D  ->  B == D
3244         Y = B;
3245         Z = D;
3246       } else if (A == D) {
3247         // D + B == C + D  ->  B == C
3248         Y = B;
3249         Z = C;
3250       } else if (B == C) {
3251         // A + C == C + D  ->  A == D
3252         Y = A;
3253         Z = D;
3254       } else {
3255         assert(B == D);
3256         // A + D == C + D  ->  A == C
3257         Y = A;
3258         Z = C;
3259       }
3260       if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3261         return V;
3262     }
3263   }
3264 
3265   if (LBO)
3266     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3267       return V;
3268 
3269   if (RBO)
3270     if (Value *V = simplifyICmpWithBinOpOnLHS(
3271             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3272       return V;
3273 
3274   // 0 - (zext X) pred C
3275   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3276     const APInt *C;
3277     if (match(RHS, m_APInt(C))) {
3278       if (C->isStrictlyPositive()) {
3279         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3280           return ConstantInt::getTrue(getCompareTy(RHS));
3281         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3282           return ConstantInt::getFalse(getCompareTy(RHS));
3283       }
3284       if (C->isNonNegative()) {
3285         if (Pred == ICmpInst::ICMP_SLE)
3286           return ConstantInt::getTrue(getCompareTy(RHS));
3287         if (Pred == ICmpInst::ICMP_SGT)
3288           return ConstantInt::getFalse(getCompareTy(RHS));
3289       }
3290     }
3291   }
3292 
3293   //   If C2 is a power-of-2 and C is not:
3294   //   (C2 << X) == C --> false
3295   //   (C2 << X) != C --> true
3296   const APInt *C;
3297   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3298       match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3299     // C2 << X can equal zero in some circumstances.
3300     // This simplification might be unsafe if C is zero.
3301     //
3302     // We know it is safe if:
3303     // - The shift is nsw. We can't shift out the one bit.
3304     // - The shift is nuw. We can't shift out the one bit.
3305     // - C2 is one.
3306     // - C isn't zero.
3307     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3308         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3309         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3310       if (Pred == ICmpInst::ICMP_EQ)
3311         return ConstantInt::getFalse(getCompareTy(RHS));
3312       if (Pred == ICmpInst::ICMP_NE)
3313         return ConstantInt::getTrue(getCompareTy(RHS));
3314     }
3315   }
3316 
3317   // TODO: This is overly constrained. LHS can be any power-of-2.
3318   // (1 << X)  >u 0x8000 --> false
3319   // (1 << X) <=u 0x8000 --> true
3320   if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
3321     if (Pred == ICmpInst::ICMP_UGT)
3322       return ConstantInt::getFalse(getCompareTy(RHS));
3323     if (Pred == ICmpInst::ICMP_ULE)
3324       return ConstantInt::getTrue(getCompareTy(RHS));
3325   }
3326 
3327   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3328       LBO->getOperand(1) == RBO->getOperand(1)) {
3329     switch (LBO->getOpcode()) {
3330     default:
3331       break;
3332     case Instruction::UDiv:
3333     case Instruction::LShr:
3334       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3335           !Q.IIQ.isExact(RBO))
3336         break;
3337       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3338                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3339         return V;
3340       break;
3341     case Instruction::SDiv:
3342       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3343           !Q.IIQ.isExact(RBO))
3344         break;
3345       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3346                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3347         return V;
3348       break;
3349     case Instruction::AShr:
3350       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3351         break;
3352       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3353                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3354         return V;
3355       break;
3356     case Instruction::Shl: {
3357       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3358       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3359       if (!NUW && !NSW)
3360         break;
3361       if (!NSW && ICmpInst::isSigned(Pred))
3362         break;
3363       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3364                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3365         return V;
3366       break;
3367     }
3368     }
3369   }
3370   return nullptr;
3371 }
3372 
3373 /// simplify integer comparisons where at least one operand of the compare
3374 /// matches an integer min/max idiom.
3375 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3376                                      Value *RHS, const SimplifyQuery &Q,
3377                                      unsigned MaxRecurse) {
3378   Type *ITy = getCompareTy(LHS); // The return type.
3379   Value *A, *B;
3380   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3381   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3382 
3383   // Signed variants on "max(a,b)>=a -> true".
3384   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3385     if (A != RHS)
3386       std::swap(A, B);       // smax(A, B) pred A.
3387     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3388     // We analyze this as smax(A, B) pred A.
3389     P = Pred;
3390   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3391              (A == LHS || B == LHS)) {
3392     if (A != LHS)
3393       std::swap(A, B);       // A pred smax(A, B).
3394     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3395     // We analyze this as smax(A, B) swapped-pred A.
3396     P = CmpInst::getSwappedPredicate(Pred);
3397   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3398              (A == RHS || B == RHS)) {
3399     if (A != RHS)
3400       std::swap(A, B);       // smin(A, B) pred A.
3401     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3402     // We analyze this as smax(-A, -B) swapped-pred -A.
3403     // Note that we do not need to actually form -A or -B thanks to EqP.
3404     P = CmpInst::getSwappedPredicate(Pred);
3405   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3406              (A == LHS || B == LHS)) {
3407     if (A != LHS)
3408       std::swap(A, B);       // A pred smin(A, B).
3409     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3410     // We analyze this as smax(-A, -B) pred -A.
3411     // Note that we do not need to actually form -A or -B thanks to EqP.
3412     P = Pred;
3413   }
3414   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3415     // Cases correspond to "max(A, B) p A".
3416     switch (P) {
3417     default:
3418       break;
3419     case CmpInst::ICMP_EQ:
3420     case CmpInst::ICMP_SLE:
3421       // Equivalent to "A EqP B".  This may be the same as the condition tested
3422       // in the max/min; if so, we can just return that.
3423       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3424         return V;
3425       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3426         return V;
3427       // Otherwise, see if "A EqP B" simplifies.
3428       if (MaxRecurse)
3429         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3430           return V;
3431       break;
3432     case CmpInst::ICMP_NE:
3433     case CmpInst::ICMP_SGT: {
3434       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3435       // Equivalent to "A InvEqP B".  This may be the same as the condition
3436       // tested in the max/min; if so, we can just return that.
3437       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3438         return V;
3439       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3440         return V;
3441       // Otherwise, see if "A InvEqP B" simplifies.
3442       if (MaxRecurse)
3443         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3444           return V;
3445       break;
3446     }
3447     case CmpInst::ICMP_SGE:
3448       // Always true.
3449       return getTrue(ITy);
3450     case CmpInst::ICMP_SLT:
3451       // Always false.
3452       return getFalse(ITy);
3453     }
3454   }
3455 
3456   // Unsigned variants on "max(a,b)>=a -> true".
3457   P = CmpInst::BAD_ICMP_PREDICATE;
3458   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3459     if (A != RHS)
3460       std::swap(A, B);       // umax(A, B) pred A.
3461     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3462     // We analyze this as umax(A, B) pred A.
3463     P = Pred;
3464   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3465              (A == LHS || B == LHS)) {
3466     if (A != LHS)
3467       std::swap(A, B);       // A pred umax(A, B).
3468     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3469     // We analyze this as umax(A, B) swapped-pred A.
3470     P = CmpInst::getSwappedPredicate(Pred);
3471   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3472              (A == RHS || B == RHS)) {
3473     if (A != RHS)
3474       std::swap(A, B);       // umin(A, B) pred A.
3475     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3476     // We analyze this as umax(-A, -B) swapped-pred -A.
3477     // Note that we do not need to actually form -A or -B thanks to EqP.
3478     P = CmpInst::getSwappedPredicate(Pred);
3479   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3480              (A == LHS || B == LHS)) {
3481     if (A != LHS)
3482       std::swap(A, B);       // A pred umin(A, B).
3483     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3484     // We analyze this as umax(-A, -B) pred -A.
3485     // Note that we do not need to actually form -A or -B thanks to EqP.
3486     P = Pred;
3487   }
3488   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3489     // Cases correspond to "max(A, B) p A".
3490     switch (P) {
3491     default:
3492       break;
3493     case CmpInst::ICMP_EQ:
3494     case CmpInst::ICMP_ULE:
3495       // Equivalent to "A EqP B".  This may be the same as the condition tested
3496       // in the max/min; if so, we can just return that.
3497       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3498         return V;
3499       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3500         return V;
3501       // Otherwise, see if "A EqP B" simplifies.
3502       if (MaxRecurse)
3503         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3504           return V;
3505       break;
3506     case CmpInst::ICMP_NE:
3507     case CmpInst::ICMP_UGT: {
3508       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3509       // Equivalent to "A InvEqP B".  This may be the same as the condition
3510       // tested in the max/min; if so, we can just return that.
3511       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3512         return V;
3513       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3514         return V;
3515       // Otherwise, see if "A InvEqP B" simplifies.
3516       if (MaxRecurse)
3517         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3518           return V;
3519       break;
3520     }
3521     case CmpInst::ICMP_UGE:
3522       return getTrue(ITy);
3523     case CmpInst::ICMP_ULT:
3524       return getFalse(ITy);
3525     }
3526   }
3527 
3528   // Comparing 1 each of min/max with a common operand?
3529   // Canonicalize min operand to RHS.
3530   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3531       match(LHS, m_SMin(m_Value(), m_Value()))) {
3532     std::swap(LHS, RHS);
3533     Pred = ICmpInst::getSwappedPredicate(Pred);
3534   }
3535 
3536   Value *C, *D;
3537   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3538       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3539       (A == C || A == D || B == C || B == D)) {
3540     // smax(A, B) >=s smin(A, D) --> true
3541     if (Pred == CmpInst::ICMP_SGE)
3542       return getTrue(ITy);
3543     // smax(A, B) <s smin(A, D) --> false
3544     if (Pred == CmpInst::ICMP_SLT)
3545       return getFalse(ITy);
3546   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3547              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3548              (A == C || A == D || B == C || B == D)) {
3549     // umax(A, B) >=u umin(A, D) --> true
3550     if (Pred == CmpInst::ICMP_UGE)
3551       return getTrue(ITy);
3552     // umax(A, B) <u umin(A, D) --> false
3553     if (Pred == CmpInst::ICMP_ULT)
3554       return getFalse(ITy);
3555   }
3556 
3557   return nullptr;
3558 }
3559 
3560 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3561                                                Value *LHS, Value *RHS,
3562                                                const SimplifyQuery &Q) {
3563   // Gracefully handle instructions that have not been inserted yet.
3564   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3565     return nullptr;
3566 
3567   for (Value *AssumeBaseOp : {LHS, RHS}) {
3568     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3569       if (!AssumeVH)
3570         continue;
3571 
3572       CallInst *Assume = cast<CallInst>(AssumeVH);
3573       if (Optional<bool> Imp = isImpliedCondition(Assume->getArgOperand(0),
3574                                                   Predicate, LHS, RHS, Q.DL))
3575         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3576           return ConstantInt::get(getCompareTy(LHS), *Imp);
3577     }
3578   }
3579 
3580   return nullptr;
3581 }
3582 
3583 /// Given operands for an ICmpInst, see if we can fold the result.
3584 /// If not, this returns null.
3585 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3586                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3587   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3588   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3589 
3590   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3591     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3592       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3593 
3594     // If we have a constant, make sure it is on the RHS.
3595     std::swap(LHS, RHS);
3596     Pred = CmpInst::getSwappedPredicate(Pred);
3597   }
3598   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3599 
3600   Type *ITy = getCompareTy(LHS); // The return type.
3601 
3602   // icmp poison, X -> poison
3603   if (isa<PoisonValue>(RHS))
3604     return PoisonValue::get(ITy);
3605 
3606   // For EQ and NE, we can always pick a value for the undef to make the
3607   // predicate pass or fail, so we can return undef.
3608   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3609   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3610     return UndefValue::get(ITy);
3611 
3612   // icmp X, X -> true/false
3613   // icmp X, undef -> true/false because undef could be X.
3614   if (LHS == RHS || Q.isUndefValue(RHS))
3615     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3616 
3617   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3618     return V;
3619 
3620   // TODO: Sink/common this with other potentially expensive calls that use
3621   //       ValueTracking? See comment below for isKnownNonEqual().
3622   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3623     return V;
3624 
3625   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3626     return V;
3627 
3628   // If both operands have range metadata, use the metadata
3629   // to simplify the comparison.
3630   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3631     auto RHS_Instr = cast<Instruction>(RHS);
3632     auto LHS_Instr = cast<Instruction>(LHS);
3633 
3634     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3635         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3636       auto RHS_CR = getConstantRangeFromMetadata(
3637           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3638       auto LHS_CR = getConstantRangeFromMetadata(
3639           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3640 
3641       if (LHS_CR.icmp(Pred, RHS_CR))
3642         return ConstantInt::getTrue(RHS->getContext());
3643 
3644       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3645         return ConstantInt::getFalse(RHS->getContext());
3646     }
3647   }
3648 
3649   // Compare of cast, for example (zext X) != 0 -> X != 0
3650   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3651     Instruction *LI = cast<CastInst>(LHS);
3652     Value *SrcOp = LI->getOperand(0);
3653     Type *SrcTy = SrcOp->getType();
3654     Type *DstTy = LI->getType();
3655 
3656     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3657     // if the integer type is the same size as the pointer type.
3658     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3659         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3660       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3661         // Transfer the cast to the constant.
3662         if (Value *V = simplifyICmpInst(Pred, SrcOp,
3663                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3664                                         Q, MaxRecurse - 1))
3665           return V;
3666       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3667         if (RI->getOperand(0)->getType() == SrcTy)
3668           // Compare without the cast.
3669           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3670                                           MaxRecurse - 1))
3671             return V;
3672       }
3673     }
3674 
3675     if (isa<ZExtInst>(LHS)) {
3676       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3677       // same type.
3678       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3679         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3680           // Compare X and Y.  Note that signed predicates become unsigned.
3681           if (Value *V =
3682                   simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
3683                                    RI->getOperand(0), Q, MaxRecurse - 1))
3684             return V;
3685       }
3686       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3687       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3688         if (SrcOp == RI->getOperand(0)) {
3689           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3690             return ConstantInt::getTrue(ITy);
3691           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3692             return ConstantInt::getFalse(ITy);
3693         }
3694       }
3695       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3696       // too.  If not, then try to deduce the result of the comparison.
3697       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3698         // Compute the constant that would happen if we truncated to SrcTy then
3699         // reextended to DstTy.
3700         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3701         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3702 
3703         // If the re-extended constant didn't change then this is effectively
3704         // also a case of comparing two zero-extended values.
3705         if (RExt == CI && MaxRecurse)
3706           if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3707                                           SrcOp, Trunc, Q, MaxRecurse - 1))
3708             return V;
3709 
3710         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3711         // there.  Use this to work out the result of the comparison.
3712         if (RExt != CI) {
3713           switch (Pred) {
3714           default:
3715             llvm_unreachable("Unknown ICmp predicate!");
3716           // LHS <u RHS.
3717           case ICmpInst::ICMP_EQ:
3718           case ICmpInst::ICMP_UGT:
3719           case ICmpInst::ICMP_UGE:
3720             return ConstantInt::getFalse(CI->getContext());
3721 
3722           case ICmpInst::ICMP_NE:
3723           case ICmpInst::ICMP_ULT:
3724           case ICmpInst::ICMP_ULE:
3725             return ConstantInt::getTrue(CI->getContext());
3726 
3727           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3728           // is non-negative then LHS <s RHS.
3729           case ICmpInst::ICMP_SGT:
3730           case ICmpInst::ICMP_SGE:
3731             return CI->getValue().isNegative()
3732                        ? ConstantInt::getTrue(CI->getContext())
3733                        : ConstantInt::getFalse(CI->getContext());
3734 
3735           case ICmpInst::ICMP_SLT:
3736           case ICmpInst::ICMP_SLE:
3737             return CI->getValue().isNegative()
3738                        ? ConstantInt::getFalse(CI->getContext())
3739                        : ConstantInt::getTrue(CI->getContext());
3740           }
3741         }
3742       }
3743     }
3744 
3745     if (isa<SExtInst>(LHS)) {
3746       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3747       // same type.
3748       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3749         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3750           // Compare X and Y.  Note that the predicate does not change.
3751           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3752                                           MaxRecurse - 1))
3753             return V;
3754       }
3755       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3756       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3757         if (SrcOp == RI->getOperand(0)) {
3758           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3759             return ConstantInt::getTrue(ITy);
3760           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3761             return ConstantInt::getFalse(ITy);
3762         }
3763       }
3764       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3765       // too.  If not, then try to deduce the result of the comparison.
3766       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3767         // Compute the constant that would happen if we truncated to SrcTy then
3768         // reextended to DstTy.
3769         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3770         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3771 
3772         // If the re-extended constant didn't change then this is effectively
3773         // also a case of comparing two sign-extended values.
3774         if (RExt == CI && MaxRecurse)
3775           if (Value *V =
3776                   simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
3777             return V;
3778 
3779         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3780         // bits there.  Use this to work out the result of the comparison.
3781         if (RExt != CI) {
3782           switch (Pred) {
3783           default:
3784             llvm_unreachable("Unknown ICmp predicate!");
3785           case ICmpInst::ICMP_EQ:
3786             return ConstantInt::getFalse(CI->getContext());
3787           case ICmpInst::ICMP_NE:
3788             return ConstantInt::getTrue(CI->getContext());
3789 
3790           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3791           // LHS >s RHS.
3792           case ICmpInst::ICMP_SGT:
3793           case ICmpInst::ICMP_SGE:
3794             return CI->getValue().isNegative()
3795                        ? ConstantInt::getTrue(CI->getContext())
3796                        : ConstantInt::getFalse(CI->getContext());
3797           case ICmpInst::ICMP_SLT:
3798           case ICmpInst::ICMP_SLE:
3799             return CI->getValue().isNegative()
3800                        ? ConstantInt::getFalse(CI->getContext())
3801                        : ConstantInt::getTrue(CI->getContext());
3802 
3803           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3804           // LHS >u RHS.
3805           case ICmpInst::ICMP_UGT:
3806           case ICmpInst::ICMP_UGE:
3807             // Comparison is true iff the LHS <s 0.
3808             if (MaxRecurse)
3809               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3810                                               Constant::getNullValue(SrcTy), Q,
3811                                               MaxRecurse - 1))
3812                 return V;
3813             break;
3814           case ICmpInst::ICMP_ULT:
3815           case ICmpInst::ICMP_ULE:
3816             // Comparison is true iff the LHS >=s 0.
3817             if (MaxRecurse)
3818               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3819                                               Constant::getNullValue(SrcTy), Q,
3820                                               MaxRecurse - 1))
3821                 return V;
3822             break;
3823           }
3824         }
3825       }
3826     }
3827   }
3828 
3829   // icmp eq|ne X, Y -> false|true if X != Y
3830   // This is potentially expensive, and we have already computedKnownBits for
3831   // compares with 0 above here, so only try this for a non-zero compare.
3832   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
3833       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3834     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3835   }
3836 
3837   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3838     return V;
3839 
3840   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3841     return V;
3842 
3843   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3844     return V;
3845 
3846   // Simplify comparisons of related pointers using a powerful, recursive
3847   // GEP-walk when we have target data available..
3848   if (LHS->getType()->isPointerTy())
3849     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3850       return C;
3851   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3852     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3853       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3854               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3855           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3856               Q.DL.getTypeSizeInBits(CRHS->getType()))
3857         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3858                                          CRHS->getPointerOperand(), Q))
3859           return C;
3860 
3861   // If the comparison is with the result of a select instruction, check whether
3862   // comparing with either branch of the select always yields the same value.
3863   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3864     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3865       return V;
3866 
3867   // If the comparison is with the result of a phi instruction, check whether
3868   // doing the compare with each incoming phi value yields a common result.
3869   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3870     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3871       return V;
3872 
3873   return nullptr;
3874 }
3875 
3876 Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3877                               const SimplifyQuery &Q) {
3878   return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3879 }
3880 
3881 /// Given operands for an FCmpInst, see if we can fold the result.
3882 /// If not, this returns null.
3883 static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3884                                FastMathFlags FMF, const SimplifyQuery &Q,
3885                                unsigned MaxRecurse) {
3886   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3887   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3888 
3889   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3890     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3891       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3892 
3893     // If we have a constant, make sure it is on the RHS.
3894     std::swap(LHS, RHS);
3895     Pred = CmpInst::getSwappedPredicate(Pred);
3896   }
3897 
3898   // Fold trivial predicates.
3899   Type *RetTy = getCompareTy(LHS);
3900   if (Pred == FCmpInst::FCMP_FALSE)
3901     return getFalse(RetTy);
3902   if (Pred == FCmpInst::FCMP_TRUE)
3903     return getTrue(RetTy);
3904 
3905   // Fold (un)ordered comparison if we can determine there are no NaNs.
3906   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3907     if (FMF.noNaNs() ||
3908         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3909       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3910 
3911   // NaN is unordered; NaN is not ordered.
3912   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3913          "Comparison must be either ordered or unordered");
3914   if (match(RHS, m_NaN()))
3915     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3916 
3917   // fcmp pred x, poison and  fcmp pred poison, x
3918   // fold to poison
3919   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
3920     return PoisonValue::get(RetTy);
3921 
3922   // fcmp pred x, undef  and  fcmp pred undef, x
3923   // fold to true if unordered, false if ordered
3924   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3925     // Choosing NaN for the undef will always make unordered comparison succeed
3926     // and ordered comparison fail.
3927     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3928   }
3929 
3930   // fcmp x,x -> true/false.  Not all compares are foldable.
3931   if (LHS == RHS) {
3932     if (CmpInst::isTrueWhenEqual(Pred))
3933       return getTrue(RetTy);
3934     if (CmpInst::isFalseWhenEqual(Pred))
3935       return getFalse(RetTy);
3936   }
3937 
3938   // Handle fcmp with constant RHS.
3939   // TODO: Use match with a specific FP value, so these work with vectors with
3940   // undef lanes.
3941   const APFloat *C;
3942   if (match(RHS, m_APFloat(C))) {
3943     // Check whether the constant is an infinity.
3944     if (C->isInfinity()) {
3945       if (C->isNegative()) {
3946         switch (Pred) {
3947         case FCmpInst::FCMP_OLT:
3948           // No value is ordered and less than negative infinity.
3949           return getFalse(RetTy);
3950         case FCmpInst::FCMP_UGE:
3951           // All values are unordered with or at least negative infinity.
3952           return getTrue(RetTy);
3953         default:
3954           break;
3955         }
3956       } else {
3957         switch (Pred) {
3958         case FCmpInst::FCMP_OGT:
3959           // No value is ordered and greater than infinity.
3960           return getFalse(RetTy);
3961         case FCmpInst::FCMP_ULE:
3962           // All values are unordered with and at most infinity.
3963           return getTrue(RetTy);
3964         default:
3965           break;
3966         }
3967       }
3968 
3969       // LHS == Inf
3970       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3971         return getFalse(RetTy);
3972       // LHS != Inf
3973       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3974         return getTrue(RetTy);
3975       // LHS == Inf || LHS == NaN
3976       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3977           isKnownNeverNaN(LHS, Q.TLI))
3978         return getFalse(RetTy);
3979       // LHS != Inf && LHS != NaN
3980       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3981           isKnownNeverNaN(LHS, Q.TLI))
3982         return getTrue(RetTy);
3983     }
3984     if (C->isNegative() && !C->isNegZero()) {
3985       assert(!C->isNaN() && "Unexpected NaN constant!");
3986       // TODO: We can catch more cases by using a range check rather than
3987       //       relying on CannotBeOrderedLessThanZero.
3988       switch (Pred) {
3989       case FCmpInst::FCMP_UGE:
3990       case FCmpInst::FCMP_UGT:
3991       case FCmpInst::FCMP_UNE:
3992         // (X >= 0) implies (X > C) when (C < 0)
3993         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3994           return getTrue(RetTy);
3995         break;
3996       case FCmpInst::FCMP_OEQ:
3997       case FCmpInst::FCMP_OLE:
3998       case FCmpInst::FCMP_OLT:
3999         // (X >= 0) implies !(X < C) when (C < 0)
4000         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
4001           return getFalse(RetTy);
4002         break;
4003       default:
4004         break;
4005       }
4006     }
4007 
4008     // Check comparison of [minnum/maxnum with constant] with other constant.
4009     const APFloat *C2;
4010     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
4011          *C2 < *C) ||
4012         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
4013          *C2 > *C)) {
4014       bool IsMaxNum =
4015           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
4016       // The ordered relationship and minnum/maxnum guarantee that we do not
4017       // have NaN constants, so ordered/unordered preds are handled the same.
4018       switch (Pred) {
4019       case FCmpInst::FCMP_OEQ:
4020       case FCmpInst::FCMP_UEQ:
4021         // minnum(X, LesserC)  == C --> false
4022         // maxnum(X, GreaterC) == C --> false
4023         return getFalse(RetTy);
4024       case FCmpInst::FCMP_ONE:
4025       case FCmpInst::FCMP_UNE:
4026         // minnum(X, LesserC)  != C --> true
4027         // maxnum(X, GreaterC) != C --> true
4028         return getTrue(RetTy);
4029       case FCmpInst::FCMP_OGE:
4030       case FCmpInst::FCMP_UGE:
4031       case FCmpInst::FCMP_OGT:
4032       case FCmpInst::FCMP_UGT:
4033         // minnum(X, LesserC)  >= C --> false
4034         // minnum(X, LesserC)  >  C --> false
4035         // maxnum(X, GreaterC) >= C --> true
4036         // maxnum(X, GreaterC) >  C --> true
4037         return ConstantInt::get(RetTy, IsMaxNum);
4038       case FCmpInst::FCMP_OLE:
4039       case FCmpInst::FCMP_ULE:
4040       case FCmpInst::FCMP_OLT:
4041       case FCmpInst::FCMP_ULT:
4042         // minnum(X, LesserC)  <= C --> true
4043         // minnum(X, LesserC)  <  C --> true
4044         // maxnum(X, GreaterC) <= C --> false
4045         // maxnum(X, GreaterC) <  C --> false
4046         return ConstantInt::get(RetTy, !IsMaxNum);
4047       default:
4048         // TRUE/FALSE/ORD/UNO should be handled before this.
4049         llvm_unreachable("Unexpected fcmp predicate");
4050       }
4051     }
4052   }
4053 
4054   if (match(RHS, m_AnyZeroFP())) {
4055     switch (Pred) {
4056     case FCmpInst::FCMP_OGE:
4057     case FCmpInst::FCMP_ULT:
4058       // Positive or zero X >= 0.0 --> true
4059       // Positive or zero X <  0.0 --> false
4060       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
4061           CannotBeOrderedLessThanZero(LHS, Q.TLI))
4062         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4063       break;
4064     case FCmpInst::FCMP_UGE:
4065     case FCmpInst::FCMP_OLT:
4066       // Positive or zero or nan X >= 0.0 --> true
4067       // Positive or zero or nan X <  0.0 --> false
4068       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
4069         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4070       break;
4071     default:
4072       break;
4073     }
4074   }
4075 
4076   // If the comparison is with the result of a select instruction, check whether
4077   // comparing with either branch of the select always yields the same value.
4078   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4079     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4080       return V;
4081 
4082   // If the comparison is with the result of a phi instruction, check whether
4083   // doing the compare with each incoming phi value yields a common result.
4084   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4085     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4086       return V;
4087 
4088   return nullptr;
4089 }
4090 
4091 Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4092                               FastMathFlags FMF, const SimplifyQuery &Q) {
4093   return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4094 }
4095 
4096 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4097                                      const SimplifyQuery &Q,
4098                                      bool AllowRefinement,
4099                                      unsigned MaxRecurse) {
4100   assert(!Op->getType()->isVectorTy() && "This is not safe for vectors");
4101 
4102   // Trivial replacement.
4103   if (V == Op)
4104     return RepOp;
4105 
4106   // We cannot replace a constant, and shouldn't even try.
4107   if (isa<Constant>(Op))
4108     return nullptr;
4109 
4110   auto *I = dyn_cast<Instruction>(V);
4111   if (!I || !is_contained(I->operands(), Op))
4112     return nullptr;
4113 
4114   // Replace Op with RepOp in instruction operands.
4115   SmallVector<Value *, 8> NewOps(I->getNumOperands());
4116   transform(I->operands(), NewOps.begin(),
4117             [&](Value *V) { return V == Op ? RepOp : V; });
4118 
4119   if (!AllowRefinement) {
4120     // General InstSimplify functions may refine the result, e.g. by returning
4121     // a constant for a potentially poison value. To avoid this, implement only
4122     // a few non-refining but profitable transforms here.
4123 
4124     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4125       unsigned Opcode = BO->getOpcode();
4126       // id op x -> x, x op id -> x
4127       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4128         return NewOps[1];
4129       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4130                                                       /* RHS */ true))
4131         return NewOps[0];
4132 
4133       // x & x -> x, x | x -> x
4134       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4135           NewOps[0] == NewOps[1])
4136         return NewOps[0];
4137     }
4138 
4139     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4140       // getelementptr x, 0 -> x
4141       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
4142           !GEP->isInBounds())
4143         return NewOps[0];
4144     }
4145   } else if (MaxRecurse) {
4146     // The simplification queries below may return the original value. Consider:
4147     //   %div = udiv i32 %arg, %arg2
4148     //   %mul = mul nsw i32 %div, %arg2
4149     //   %cmp = icmp eq i32 %mul, %arg
4150     //   %sel = select i1 %cmp, i32 %div, i32 undef
4151     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4152     // simplifies back to %arg. This can only happen because %mul does not
4153     // dominate %div. To ensure a consistent return value contract, we make sure
4154     // that this case returns nullptr as well.
4155     auto PreventSelfSimplify = [V](Value *Simplified) {
4156       return Simplified != V ? Simplified : nullptr;
4157     };
4158 
4159     if (auto *B = dyn_cast<BinaryOperator>(I))
4160       return PreventSelfSimplify(simplifyBinOp(B->getOpcode(), NewOps[0],
4161                                                NewOps[1], Q, MaxRecurse - 1));
4162 
4163     if (CmpInst *C = dyn_cast<CmpInst>(I))
4164       return PreventSelfSimplify(simplifyCmpInst(C->getPredicate(), NewOps[0],
4165                                                  NewOps[1], Q, MaxRecurse - 1));
4166 
4167     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4168       return PreventSelfSimplify(simplifyGEPInst(
4169           GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
4170           GEP->isInBounds(), Q, MaxRecurse - 1));
4171 
4172     if (isa<SelectInst>(I))
4173       return PreventSelfSimplify(simplifySelectInst(
4174           NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse - 1));
4175     // TODO: We could hand off more cases to instsimplify here.
4176   }
4177 
4178   // If all operands are constant after substituting Op for RepOp then we can
4179   // constant fold the instruction.
4180   SmallVector<Constant *, 8> ConstOps;
4181   for (Value *NewOp : NewOps) {
4182     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4183       ConstOps.push_back(ConstOp);
4184     else
4185       return nullptr;
4186   }
4187 
4188   // Consider:
4189   //   %cmp = icmp eq i32 %x, 2147483647
4190   //   %add = add nsw i32 %x, 1
4191   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4192   //
4193   // We can't replace %sel with %add unless we strip away the flags (which
4194   // will be done in InstCombine).
4195   // TODO: This may be unsound, because it only catches some forms of
4196   // refinement.
4197   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4198     return nullptr;
4199 
4200   if (CmpInst *C = dyn_cast<CmpInst>(I))
4201     return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4202                                            ConstOps[1], Q.DL, Q.TLI);
4203 
4204   if (LoadInst *LI = dyn_cast<LoadInst>(I))
4205     if (!LI->isVolatile())
4206       return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4207 
4208   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4209 }
4210 
4211 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4212                                     const SimplifyQuery &Q,
4213                                     bool AllowRefinement) {
4214   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4215                                   RecursionLimit);
4216 }
4217 
4218 /// Try to simplify a select instruction when its condition operand is an
4219 /// integer comparison where one operand of the compare is a constant.
4220 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4221                                     const APInt *Y, bool TrueWhenUnset) {
4222   const APInt *C;
4223 
4224   // (X & Y) == 0 ? X & ~Y : X  --> X
4225   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4226   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4227       *Y == ~*C)
4228     return TrueWhenUnset ? FalseVal : TrueVal;
4229 
4230   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4231   // (X & Y) != 0 ? X : X & ~Y  --> X
4232   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4233       *Y == ~*C)
4234     return TrueWhenUnset ? FalseVal : TrueVal;
4235 
4236   if (Y->isPowerOf2()) {
4237     // (X & Y) == 0 ? X | Y : X  --> X | Y
4238     // (X & Y) != 0 ? X | Y : X  --> X
4239     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4240         *Y == *C)
4241       return TrueWhenUnset ? TrueVal : FalseVal;
4242 
4243     // (X & Y) == 0 ? X : X | Y  --> X
4244     // (X & Y) != 0 ? X : X | Y  --> X | Y
4245     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4246         *Y == *C)
4247       return TrueWhenUnset ? TrueVal : FalseVal;
4248   }
4249 
4250   return nullptr;
4251 }
4252 
4253 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4254 /// eq/ne.
4255 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4256                                            ICmpInst::Predicate Pred,
4257                                            Value *TrueVal, Value *FalseVal) {
4258   Value *X;
4259   APInt Mask;
4260   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4261     return nullptr;
4262 
4263   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4264                                Pred == ICmpInst::ICMP_EQ);
4265 }
4266 
4267 /// Try to simplify a select instruction when its condition operand is an
4268 /// integer comparison.
4269 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4270                                          Value *FalseVal,
4271                                          const SimplifyQuery &Q,
4272                                          unsigned MaxRecurse) {
4273   ICmpInst::Predicate Pred;
4274   Value *CmpLHS, *CmpRHS;
4275   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4276     return nullptr;
4277 
4278   // Canonicalize ne to eq predicate.
4279   if (Pred == ICmpInst::ICMP_NE) {
4280     Pred = ICmpInst::ICMP_EQ;
4281     std::swap(TrueVal, FalseVal);
4282   }
4283 
4284   // Check for integer min/max with a limit constant:
4285   // X > MIN_INT ? X : MIN_INT --> X
4286   // X < MAX_INT ? X : MAX_INT --> X
4287   if (TrueVal->getType()->isIntOrIntVectorTy()) {
4288     Value *X, *Y;
4289     SelectPatternFlavor SPF =
4290         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4291                                      X, Y)
4292             .Flavor;
4293     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4294       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4295                                     X->getType()->getScalarSizeInBits());
4296       if (match(Y, m_SpecificInt(LimitC)))
4297         return X;
4298     }
4299   }
4300 
4301   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4302     Value *X;
4303     const APInt *Y;
4304     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4305       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4306                                            /*TrueWhenUnset=*/true))
4307         return V;
4308 
4309     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4310     Value *ShAmt;
4311     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4312                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4313     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4314     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4315     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4316       return X;
4317 
4318     // Test for a zero-shift-guard-op around rotates. These are used to
4319     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4320     // intrinsics do not have that problem.
4321     // We do not allow this transform for the general funnel shift case because
4322     // that would not preserve the poison safety of the original code.
4323     auto isRotate =
4324         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4325                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4326     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4327     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4328     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4329         Pred == ICmpInst::ICMP_EQ)
4330       return FalseVal;
4331 
4332     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4333     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4334     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4335         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4336       return FalseVal;
4337     if (match(TrueVal,
4338               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4339         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4340       return FalseVal;
4341   }
4342 
4343   // Check for other compares that behave like bit test.
4344   if (Value *V =
4345           simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4346     return V;
4347 
4348   // If we have a scalar equality comparison, then we know the value in one of
4349   // the arms of the select. See if substituting this value into the arm and
4350   // simplifying the result yields the same value as the other arm.
4351   // Note that the equivalence/replacement opportunity does not hold for vectors
4352   // because each element of a vector select is chosen independently.
4353   if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
4354     if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4355                                /* AllowRefinement */ false,
4356                                MaxRecurse) == TrueVal ||
4357         simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4358                                /* AllowRefinement */ false,
4359                                MaxRecurse) == TrueVal)
4360       return FalseVal;
4361     if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4362                                /* AllowRefinement */ true,
4363                                MaxRecurse) == FalseVal ||
4364         simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4365                                /* AllowRefinement */ true,
4366                                MaxRecurse) == FalseVal)
4367       return FalseVal;
4368   }
4369 
4370   return nullptr;
4371 }
4372 
4373 /// Try to simplify a select instruction when its condition operand is a
4374 /// floating-point comparison.
4375 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4376                                      const SimplifyQuery &Q) {
4377   FCmpInst::Predicate Pred;
4378   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4379       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4380     return nullptr;
4381 
4382   // This transform is safe if we do not have (do not care about) -0.0 or if
4383   // at least one operand is known to not be -0.0. Otherwise, the select can
4384   // change the sign of a zero operand.
4385   bool HasNoSignedZeros =
4386       Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
4387   const APFloat *C;
4388   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4389       (match(F, m_APFloat(C)) && C->isNonZero())) {
4390     // (T == F) ? T : F --> F
4391     // (F == T) ? T : F --> F
4392     if (Pred == FCmpInst::FCMP_OEQ)
4393       return F;
4394 
4395     // (T != F) ? T : F --> T
4396     // (F != T) ? T : F --> T
4397     if (Pred == FCmpInst::FCMP_UNE)
4398       return T;
4399   }
4400 
4401   return nullptr;
4402 }
4403 
4404 /// Given operands for a SelectInst, see if we can fold the result.
4405 /// If not, this returns null.
4406 static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4407                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4408   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4409     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4410       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4411         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4412 
4413     // select poison, X, Y -> poison
4414     if (isa<PoisonValue>(CondC))
4415       return PoisonValue::get(TrueVal->getType());
4416 
4417     // select undef, X, Y -> X or Y
4418     if (Q.isUndefValue(CondC))
4419       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4420 
4421     // select true,  X, Y --> X
4422     // select false, X, Y --> Y
4423     // For vectors, allow undef/poison elements in the condition to match the
4424     // defined elements, so we can eliminate the select.
4425     if (match(CondC, m_One()))
4426       return TrueVal;
4427     if (match(CondC, m_Zero()))
4428       return FalseVal;
4429   }
4430 
4431   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4432          "Select must have bool or bool vector condition");
4433   assert(TrueVal->getType() == FalseVal->getType() &&
4434          "Select must have same types for true/false ops");
4435 
4436   if (Cond->getType() == TrueVal->getType()) {
4437     // select i1 Cond, i1 true, i1 false --> i1 Cond
4438     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4439       return Cond;
4440 
4441     // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4442     Value *X, *Y;
4443     if (match(FalseVal, m_ZeroInt())) {
4444       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4445           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4446         return X;
4447       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4448           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4449         return X;
4450     }
4451   }
4452 
4453   // select ?, X, X -> X
4454   if (TrueVal == FalseVal)
4455     return TrueVal;
4456 
4457   // If the true or false value is poison, we can fold to the other value.
4458   // If the true or false value is undef, we can fold to the other value as
4459   // long as the other value isn't poison.
4460   // select ?, poison, X -> X
4461   // select ?, undef,  X -> X
4462   if (isa<PoisonValue>(TrueVal) ||
4463       (Q.isUndefValue(TrueVal) &&
4464        isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
4465     return FalseVal;
4466   // select ?, X, poison -> X
4467   // select ?, X, undef  -> X
4468   if (isa<PoisonValue>(FalseVal) ||
4469       (Q.isUndefValue(FalseVal) &&
4470        isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
4471     return TrueVal;
4472 
4473   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4474   Constant *TrueC, *FalseC;
4475   if (isa<FixedVectorType>(TrueVal->getType()) &&
4476       match(TrueVal, m_Constant(TrueC)) &&
4477       match(FalseVal, m_Constant(FalseC))) {
4478     unsigned NumElts =
4479         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4480     SmallVector<Constant *, 16> NewC;
4481     for (unsigned i = 0; i != NumElts; ++i) {
4482       // Bail out on incomplete vector constants.
4483       Constant *TEltC = TrueC->getAggregateElement(i);
4484       Constant *FEltC = FalseC->getAggregateElement(i);
4485       if (!TEltC || !FEltC)
4486         break;
4487 
4488       // If the elements match (undef or not), that value is the result. If only
4489       // one element is undef, choose the defined element as the safe result.
4490       if (TEltC == FEltC)
4491         NewC.push_back(TEltC);
4492       else if (isa<PoisonValue>(TEltC) ||
4493                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4494         NewC.push_back(FEltC);
4495       else if (isa<PoisonValue>(FEltC) ||
4496                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4497         NewC.push_back(TEltC);
4498       else
4499         break;
4500     }
4501     if (NewC.size() == NumElts)
4502       return ConstantVector::get(NewC);
4503   }
4504 
4505   if (Value *V =
4506           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4507     return V;
4508 
4509   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4510     return V;
4511 
4512   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4513     return V;
4514 
4515   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4516   if (Imp)
4517     return *Imp ? TrueVal : FalseVal;
4518 
4519   return nullptr;
4520 }
4521 
4522 Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4523                                 const SimplifyQuery &Q) {
4524   return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4525 }
4526 
4527 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4528 /// If not, this returns null.
4529 static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
4530                               ArrayRef<Value *> Indices, bool InBounds,
4531                               const SimplifyQuery &Q, unsigned) {
4532   // The type of the GEP pointer operand.
4533   unsigned AS =
4534       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4535 
4536   // getelementptr P -> P.
4537   if (Indices.empty())
4538     return Ptr;
4539 
4540   // Compute the (pointer) type returned by the GEP instruction.
4541   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4542   Type *GEPTy = PointerType::get(LastType, AS);
4543   if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4544     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4545   else {
4546     for (Value *Op : Indices) {
4547       // If one of the operands is a vector, the result type is a vector of
4548       // pointers. All vector operands must have the same number of elements.
4549       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4550         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4551         break;
4552       }
4553     }
4554   }
4555 
4556   // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
4557   // it may be equivalent to a bitcast.
4558   if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
4559       Ptr->getType() == GEPTy &&
4560       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4561     return Ptr;
4562 
4563   // getelementptr poison, idx -> poison
4564   // getelementptr baseptr, poison -> poison
4565   if (isa<PoisonValue>(Ptr) ||
4566       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4567     return PoisonValue::get(GEPTy);
4568 
4569   if (Q.isUndefValue(Ptr))
4570     // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
4571     return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
4572 
4573   bool IsScalableVec =
4574       isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
4575         return isa<ScalableVectorType>(V->getType());
4576       });
4577 
4578   if (Indices.size() == 1) {
4579     // getelementptr P, 0 -> P.
4580     if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4581       return Ptr;
4582 
4583     Type *Ty = SrcTy;
4584     if (!IsScalableVec && Ty->isSized()) {
4585       Value *P;
4586       uint64_t C;
4587       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4588       // getelementptr P, N -> P if P points to a type of zero size.
4589       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
4590         return Ptr;
4591 
4592       // The following transforms are only safe if the ptrtoint cast
4593       // doesn't truncate the pointers.
4594       if (Indices[0]->getType()->getScalarSizeInBits() ==
4595           Q.DL.getPointerSizeInBits(AS)) {
4596         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
4597           return P->getType() == GEPTy &&
4598                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
4599         };
4600         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4601         if (TyAllocSize == 1 &&
4602             match(Indices[0],
4603                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
4604             CanSimplify())
4605           return P;
4606 
4607         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
4608         // size 1 << C.
4609         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4610                                            m_PtrToInt(m_Specific(Ptr))),
4611                                      m_ConstantInt(C))) &&
4612             TyAllocSize == 1ULL << C && CanSimplify())
4613           return P;
4614 
4615         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
4616         // size C.
4617         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4618                                            m_PtrToInt(m_Specific(Ptr))),
4619                                      m_SpecificInt(TyAllocSize))) &&
4620             CanSimplify())
4621           return P;
4622       }
4623     }
4624   }
4625 
4626   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4627       all_of(Indices.drop_back(1),
4628              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4629     unsigned IdxWidth =
4630         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
4631     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
4632       APInt BasePtrOffset(IdxWidth, 0);
4633       Value *StrippedBasePtr =
4634           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
4635 
4636       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4637       // inttoptr is generally conservative, this particular case is folded to
4638       // a null pointer, which will have incorrect provenance.
4639 
4640       // gep (gep V, C), (sub 0, V) -> C
4641       if (match(Indices.back(),
4642                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4643           !BasePtrOffset.isZero()) {
4644         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4645         return ConstantExpr::getIntToPtr(CI, GEPTy);
4646       }
4647       // gep (gep V, C), (xor V, -1) -> C-1
4648       if (match(Indices.back(),
4649                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4650           !BasePtrOffset.isOne()) {
4651         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4652         return ConstantExpr::getIntToPtr(CI, GEPTy);
4653       }
4654     }
4655   }
4656 
4657   // Check to see if this is constant foldable.
4658   if (!isa<Constant>(Ptr) ||
4659       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
4660     return nullptr;
4661 
4662   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
4663                                             InBounds);
4664   return ConstantFoldConstant(CE, Q.DL);
4665 }
4666 
4667 Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
4668                              bool InBounds, const SimplifyQuery &Q) {
4669   return ::simplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
4670 }
4671 
4672 /// Given operands for an InsertValueInst, see if we can fold the result.
4673 /// If not, this returns null.
4674 static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
4675                                       ArrayRef<unsigned> Idxs,
4676                                       const SimplifyQuery &Q, unsigned) {
4677   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4678     if (Constant *CVal = dyn_cast<Constant>(Val))
4679       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4680 
4681   // insertvalue x, undef, n -> x
4682   if (Q.isUndefValue(Val))
4683     return Agg;
4684 
4685   // insertvalue x, (extractvalue y, n), n
4686   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4687     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4688         EV->getIndices() == Idxs) {
4689       // insertvalue undef, (extractvalue y, n), n -> y
4690       if (Q.isUndefValue(Agg))
4691         return EV->getAggregateOperand();
4692 
4693       // insertvalue y, (extractvalue y, n), n -> y
4694       if (Agg == EV->getAggregateOperand())
4695         return Agg;
4696     }
4697 
4698   return nullptr;
4699 }
4700 
4701 Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
4702                                      ArrayRef<unsigned> Idxs,
4703                                      const SimplifyQuery &Q) {
4704   return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4705 }
4706 
4707 Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4708                                        const SimplifyQuery &Q) {
4709   // Try to constant fold.
4710   auto *VecC = dyn_cast<Constant>(Vec);
4711   auto *ValC = dyn_cast<Constant>(Val);
4712   auto *IdxC = dyn_cast<Constant>(Idx);
4713   if (VecC && ValC && IdxC)
4714     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4715 
4716   // For fixed-length vector, fold into poison if index is out of bounds.
4717   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4718     if (isa<FixedVectorType>(Vec->getType()) &&
4719         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4720       return PoisonValue::get(Vec->getType());
4721   }
4722 
4723   // If index is undef, it might be out of bounds (see above case)
4724   if (Q.isUndefValue(Idx))
4725     return PoisonValue::get(Vec->getType());
4726 
4727   // If the scalar is poison, or it is undef and there is no risk of
4728   // propagating poison from the vector value, simplify to the vector value.
4729   if (isa<PoisonValue>(Val) ||
4730       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4731     return Vec;
4732 
4733   // If we are extracting a value from a vector, then inserting it into the same
4734   // place, that's the input vector:
4735   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4736   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4737     return Vec;
4738 
4739   return nullptr;
4740 }
4741 
4742 /// Given operands for an ExtractValueInst, see if we can fold the result.
4743 /// If not, this returns null.
4744 static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4745                                        const SimplifyQuery &, unsigned) {
4746   if (auto *CAgg = dyn_cast<Constant>(Agg))
4747     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4748 
4749   // extractvalue x, (insertvalue y, elt, n), n -> elt
4750   unsigned NumIdxs = Idxs.size();
4751   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4752        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4753     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4754     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4755     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4756     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4757         Idxs.slice(0, NumCommonIdxs)) {
4758       if (NumIdxs == NumInsertValueIdxs)
4759         return IVI->getInsertedValueOperand();
4760       break;
4761     }
4762   }
4763 
4764   return nullptr;
4765 }
4766 
4767 Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4768                                       const SimplifyQuery &Q) {
4769   return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4770 }
4771 
4772 /// Given operands for an ExtractElementInst, see if we can fold the result.
4773 /// If not, this returns null.
4774 static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
4775                                          const SimplifyQuery &Q, unsigned) {
4776   auto *VecVTy = cast<VectorType>(Vec->getType());
4777   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4778     if (auto *CIdx = dyn_cast<Constant>(Idx))
4779       return ConstantExpr::getExtractElement(CVec, CIdx);
4780 
4781     if (Q.isUndefValue(Vec))
4782       return UndefValue::get(VecVTy->getElementType());
4783   }
4784 
4785   // An undef extract index can be arbitrarily chosen to be an out-of-range
4786   // index value, which would result in the instruction being poison.
4787   if (Q.isUndefValue(Idx))
4788     return PoisonValue::get(VecVTy->getElementType());
4789 
4790   // If extracting a specified index from the vector, see if we can recursively
4791   // find a previously computed scalar that was inserted into the vector.
4792   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4793     // For fixed-length vector, fold into undef if index is out of bounds.
4794     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
4795     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
4796       return PoisonValue::get(VecVTy->getElementType());
4797     // Handle case where an element is extracted from a splat.
4798     if (IdxC->getValue().ult(MinNumElts))
4799       if (auto *Splat = getSplatValue(Vec))
4800         return Splat;
4801     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4802       return Elt;
4803   } else {
4804     // The index is not relevant if our vector is a splat.
4805     if (Value *Splat = getSplatValue(Vec))
4806       return Splat;
4807   }
4808   return nullptr;
4809 }
4810 
4811 Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
4812                                         const SimplifyQuery &Q) {
4813   return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4814 }
4815 
4816 /// See if we can fold the given phi. If not, returns null.
4817 static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
4818                               const SimplifyQuery &Q) {
4819   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4820   //          here, because the PHI we may succeed simplifying to was not
4821   //          def-reachable from the original PHI!
4822 
4823   // If all of the PHI's incoming values are the same then replace the PHI node
4824   // with the common value.
4825   Value *CommonValue = nullptr;
4826   bool HasUndefInput = false;
4827   for (Value *Incoming : IncomingValues) {
4828     // If the incoming value is the phi node itself, it can safely be skipped.
4829     if (Incoming == PN)
4830       continue;
4831     if (Q.isUndefValue(Incoming)) {
4832       // Remember that we saw an undef value, but otherwise ignore them.
4833       HasUndefInput = true;
4834       continue;
4835     }
4836     if (CommonValue && Incoming != CommonValue)
4837       return nullptr; // Not the same, bail out.
4838     CommonValue = Incoming;
4839   }
4840 
4841   // If CommonValue is null then all of the incoming values were either undef or
4842   // equal to the phi node itself.
4843   if (!CommonValue)
4844     return UndefValue::get(PN->getType());
4845 
4846   if (HasUndefInput) {
4847     // We cannot start executing a trapping constant expression on more control
4848     // flow paths.
4849     auto *C = dyn_cast<Constant>(CommonValue);
4850     if (C && C->canTrap())
4851       return nullptr;
4852 
4853     // If we have a PHI node like phi(X, undef, X), where X is defined by some
4854     // instruction, we cannot return X as the result of the PHI node unless it
4855     // dominates the PHI block.
4856     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4857   }
4858 
4859   return CommonValue;
4860 }
4861 
4862 static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4863                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4864   if (auto *C = dyn_cast<Constant>(Op))
4865     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4866 
4867   if (auto *CI = dyn_cast<CastInst>(Op)) {
4868     auto *Src = CI->getOperand(0);
4869     Type *SrcTy = Src->getType();
4870     Type *MidTy = CI->getType();
4871     Type *DstTy = Ty;
4872     if (Src->getType() == Ty) {
4873       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4874       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4875       Type *SrcIntPtrTy =
4876           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4877       Type *MidIntPtrTy =
4878           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4879       Type *DstIntPtrTy =
4880           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4881       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4882                                          SrcIntPtrTy, MidIntPtrTy,
4883                                          DstIntPtrTy) == Instruction::BitCast)
4884         return Src;
4885     }
4886   }
4887 
4888   // bitcast x -> x
4889   if (CastOpc == Instruction::BitCast)
4890     if (Op->getType() == Ty)
4891       return Op;
4892 
4893   return nullptr;
4894 }
4895 
4896 Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4897                               const SimplifyQuery &Q) {
4898   return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4899 }
4900 
4901 /// For the given destination element of a shuffle, peek through shuffles to
4902 /// match a root vector source operand that contains that element in the same
4903 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4904 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4905                                    int MaskVal, Value *RootVec,
4906                                    unsigned MaxRecurse) {
4907   if (!MaxRecurse--)
4908     return nullptr;
4909 
4910   // Bail out if any mask value is undefined. That kind of shuffle may be
4911   // simplified further based on demanded bits or other folds.
4912   if (MaskVal == -1)
4913     return nullptr;
4914 
4915   // The mask value chooses which source operand we need to look at next.
4916   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4917   int RootElt = MaskVal;
4918   Value *SourceOp = Op0;
4919   if (MaskVal >= InVecNumElts) {
4920     RootElt = MaskVal - InVecNumElts;
4921     SourceOp = Op1;
4922   }
4923 
4924   // If the source operand is a shuffle itself, look through it to find the
4925   // matching root vector.
4926   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4927     return foldIdentityShuffles(
4928         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4929         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4930   }
4931 
4932   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4933   // size?
4934 
4935   // The source operand is not a shuffle. Initialize the root vector value for
4936   // this shuffle if that has not been done yet.
4937   if (!RootVec)
4938     RootVec = SourceOp;
4939 
4940   // Give up as soon as a source operand does not match the existing root value.
4941   if (RootVec != SourceOp)
4942     return nullptr;
4943 
4944   // The element must be coming from the same lane in the source vector
4945   // (although it may have crossed lanes in intermediate shuffles).
4946   if (RootElt != DestElt)
4947     return nullptr;
4948 
4949   return RootVec;
4950 }
4951 
4952 static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
4953                                         ArrayRef<int> Mask, Type *RetTy,
4954                                         const SimplifyQuery &Q,
4955                                         unsigned MaxRecurse) {
4956   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4957     return UndefValue::get(RetTy);
4958 
4959   auto *InVecTy = cast<VectorType>(Op0->getType());
4960   unsigned MaskNumElts = Mask.size();
4961   ElementCount InVecEltCount = InVecTy->getElementCount();
4962 
4963   bool Scalable = InVecEltCount.isScalable();
4964 
4965   SmallVector<int, 32> Indices;
4966   Indices.assign(Mask.begin(), Mask.end());
4967 
4968   // Canonicalization: If mask does not select elements from an input vector,
4969   // replace that input vector with poison.
4970   if (!Scalable) {
4971     bool MaskSelects0 = false, MaskSelects1 = false;
4972     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4973     for (unsigned i = 0; i != MaskNumElts; ++i) {
4974       if (Indices[i] == -1)
4975         continue;
4976       if ((unsigned)Indices[i] < InVecNumElts)
4977         MaskSelects0 = true;
4978       else
4979         MaskSelects1 = true;
4980     }
4981     if (!MaskSelects0)
4982       Op0 = PoisonValue::get(InVecTy);
4983     if (!MaskSelects1)
4984       Op1 = PoisonValue::get(InVecTy);
4985   }
4986 
4987   auto *Op0Const = dyn_cast<Constant>(Op0);
4988   auto *Op1Const = dyn_cast<Constant>(Op1);
4989 
4990   // If all operands are constant, constant fold the shuffle. This
4991   // transformation depends on the value of the mask which is not known at
4992   // compile time for scalable vectors
4993   if (Op0Const && Op1Const)
4994     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4995 
4996   // Canonicalization: if only one input vector is constant, it shall be the
4997   // second one. This transformation depends on the value of the mask which
4998   // is not known at compile time for scalable vectors
4999   if (!Scalable && Op0Const && !Op1Const) {
5000     std::swap(Op0, Op1);
5001     ShuffleVectorInst::commuteShuffleMask(Indices,
5002                                           InVecEltCount.getKnownMinValue());
5003   }
5004 
5005   // A splat of an inserted scalar constant becomes a vector constant:
5006   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
5007   // NOTE: We may have commuted above, so analyze the updated Indices, not the
5008   //       original mask constant.
5009   // NOTE: This transformation depends on the value of the mask which is not
5010   // known at compile time for scalable vectors
5011   Constant *C;
5012   ConstantInt *IndexC;
5013   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
5014                                           m_ConstantInt(IndexC)))) {
5015     // Match a splat shuffle mask of the insert index allowing undef elements.
5016     int InsertIndex = IndexC->getZExtValue();
5017     if (all_of(Indices, [InsertIndex](int MaskElt) {
5018           return MaskElt == InsertIndex || MaskElt == -1;
5019         })) {
5020       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
5021 
5022       // Shuffle mask undefs become undefined constant result elements.
5023       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
5024       for (unsigned i = 0; i != MaskNumElts; ++i)
5025         if (Indices[i] == -1)
5026           VecC[i] = UndefValue::get(C->getType());
5027       return ConstantVector::get(VecC);
5028     }
5029   }
5030 
5031   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5032   // value type is same as the input vectors' type.
5033   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
5034     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5035         is_splat(OpShuf->getShuffleMask()))
5036       return Op0;
5037 
5038   // All remaining transformation depend on the value of the mask, which is
5039   // not known at compile time for scalable vectors.
5040   if (Scalable)
5041     return nullptr;
5042 
5043   // Don't fold a shuffle with undef mask elements. This may get folded in a
5044   // better way using demanded bits or other analysis.
5045   // TODO: Should we allow this?
5046   if (is_contained(Indices, -1))
5047     return nullptr;
5048 
5049   // Check if every element of this shuffle can be mapped back to the
5050   // corresponding element of a single root vector. If so, we don't need this
5051   // shuffle. This handles simple identity shuffles as well as chains of
5052   // shuffles that may widen/narrow and/or move elements across lanes and back.
5053   Value *RootVec = nullptr;
5054   for (unsigned i = 0; i != MaskNumElts; ++i) {
5055     // Note that recursion is limited for each vector element, so if any element
5056     // exceeds the limit, this will fail to simplify.
5057     RootVec =
5058         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
5059 
5060     // We can't replace a widening/narrowing shuffle with one of its operands.
5061     if (!RootVec || RootVec->getType() != RetTy)
5062       return nullptr;
5063   }
5064   return RootVec;
5065 }
5066 
5067 /// Given operands for a ShuffleVectorInst, fold the result or return null.
5068 Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5069                                        ArrayRef<int> Mask, Type *RetTy,
5070                                        const SimplifyQuery &Q) {
5071   return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
5072 }
5073 
5074 static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
5075                               const SimplifyQuery &Q) {
5076   if (auto *C = dyn_cast<Constant>(Op))
5077     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
5078   return nullptr;
5079 }
5080 
5081 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
5082 /// returns null.
5083 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5084                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5085   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5086     return C;
5087 
5088   Value *X;
5089   // fneg (fneg X) ==> X
5090   if (match(Op, m_FNeg(m_Value(X))))
5091     return X;
5092 
5093   return nullptr;
5094 }
5095 
5096 Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
5097                               const SimplifyQuery &Q) {
5098   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5099 }
5100 
5101 static Constant *propagateNaN(Constant *In) {
5102   // If the input is a vector with undef elements, just return a default NaN.
5103   if (!In->isNaN())
5104     return ConstantFP::getNaN(In->getType());
5105 
5106   // Propagate the existing NaN constant when possible.
5107   // TODO: Should we quiet a signaling NaN?
5108   return In;
5109 }
5110 
5111 /// Perform folds that are common to any floating-point operation. This implies
5112 /// transforms based on poison/undef/NaN because the operation itself makes no
5113 /// difference to the result.
5114 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5115                               const SimplifyQuery &Q,
5116                               fp::ExceptionBehavior ExBehavior,
5117                               RoundingMode Rounding) {
5118   // Poison is independent of anything else. It always propagates from an
5119   // operand to a math result.
5120   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5121     return PoisonValue::get(Ops[0]->getType());
5122 
5123   for (Value *V : Ops) {
5124     bool IsNan = match(V, m_NaN());
5125     bool IsInf = match(V, m_Inf());
5126     bool IsUndef = Q.isUndefValue(V);
5127 
5128     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5129     // (an undef operand can be chosen to be Nan/Inf), then the result of
5130     // this operation is poison.
5131     if (FMF.noNaNs() && (IsNan || IsUndef))
5132       return PoisonValue::get(V->getType());
5133     if (FMF.noInfs() && (IsInf || IsUndef))
5134       return PoisonValue::get(V->getType());
5135 
5136     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5137       if (IsUndef || IsNan)
5138         return propagateNaN(cast<Constant>(V));
5139     } else if (ExBehavior != fp::ebStrict) {
5140       if (IsNan)
5141         return propagateNaN(cast<Constant>(V));
5142     }
5143   }
5144   return nullptr;
5145 }
5146 
5147 /// Given operands for an FAdd, see if we can fold the result.  If not, this
5148 /// returns null.
5149 static Value *
5150 simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5151                  const SimplifyQuery &Q, unsigned MaxRecurse,
5152                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5153                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5154   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5155     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5156       return C;
5157 
5158   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5159     return C;
5160 
5161   // fadd X, -0 ==> X
5162   // With strict/constrained FP, we have these possible edge cases that do
5163   // not simplify to Op0:
5164   // fadd SNaN, -0.0 --> QNaN
5165   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5166   if (canIgnoreSNaN(ExBehavior, FMF) &&
5167       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5168        FMF.noSignedZeros()))
5169     if (match(Op1, m_NegZeroFP()))
5170       return Op0;
5171 
5172   // fadd X, 0 ==> X, when we know X is not -0
5173   if (canIgnoreSNaN(ExBehavior, FMF))
5174     if (match(Op1, m_PosZeroFP()) &&
5175         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5176       return Op0;
5177 
5178   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5179     return nullptr;
5180 
5181   // With nnan: -X + X --> 0.0 (and commuted variant)
5182   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5183   // Negative zeros are allowed because we always end up with positive zero:
5184   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5185   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5186   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5187   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5188   if (FMF.noNaNs()) {
5189     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5190         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5191       return ConstantFP::getNullValue(Op0->getType());
5192 
5193     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5194         match(Op1, m_FNeg(m_Specific(Op0))))
5195       return ConstantFP::getNullValue(Op0->getType());
5196   }
5197 
5198   // (X - Y) + Y --> X
5199   // Y + (X - Y) --> X
5200   Value *X;
5201   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5202       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5203        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5204     return X;
5205 
5206   return nullptr;
5207 }
5208 
5209 /// Given operands for an FSub, see if we can fold the result.  If not, this
5210 /// returns null.
5211 static Value *
5212 simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5213                  const SimplifyQuery &Q, unsigned MaxRecurse,
5214                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5215                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5216   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5217     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5218       return C;
5219 
5220   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5221     return C;
5222 
5223   // fsub X, +0 ==> X
5224   if (canIgnoreSNaN(ExBehavior, FMF) &&
5225       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5226        FMF.noSignedZeros()))
5227     if (match(Op1, m_PosZeroFP()))
5228       return Op0;
5229 
5230   // fsub X, -0 ==> X, when we know X is not -0
5231   if (canIgnoreSNaN(ExBehavior, FMF))
5232     if (match(Op1, m_NegZeroFP()) &&
5233         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5234       return Op0;
5235 
5236   // fsub -0.0, (fsub -0.0, X) ==> X
5237   // fsub -0.0, (fneg X) ==> X
5238   Value *X;
5239   if (canIgnoreSNaN(ExBehavior, FMF))
5240     if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
5241       return X;
5242 
5243   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5244     return nullptr;
5245 
5246   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5247   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5248   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5249       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5250        match(Op1, m_FNeg(m_Value(X)))))
5251     return X;
5252 
5253   // fsub nnan x, x ==> 0.0
5254   if (FMF.noNaNs() && Op0 == Op1)
5255     return Constant::getNullValue(Op0->getType());
5256 
5257   // Y - (Y - X) --> X
5258   // (X + Y) - Y --> X
5259   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5260       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5261        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5262     return X;
5263 
5264   return nullptr;
5265 }
5266 
5267 static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5268                               const SimplifyQuery &Q, unsigned MaxRecurse,
5269                               fp::ExceptionBehavior ExBehavior,
5270                               RoundingMode Rounding) {
5271   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5272     return C;
5273 
5274   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5275     return nullptr;
5276 
5277   // fmul X, 1.0 ==> X
5278   if (match(Op1, m_FPOne()))
5279     return Op0;
5280 
5281   // fmul 1.0, X ==> X
5282   if (match(Op0, m_FPOne()))
5283     return Op1;
5284 
5285   // fmul nnan nsz X, 0 ==> 0
5286   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
5287     return ConstantFP::getNullValue(Op0->getType());
5288 
5289   // fmul nnan nsz 0, X ==> 0
5290   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5291     return ConstantFP::getNullValue(Op1->getType());
5292 
5293   // sqrt(X) * sqrt(X) --> X, if we can:
5294   // 1. Remove the intermediate rounding (reassociate).
5295   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5296   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5297   Value *X;
5298   if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
5299       FMF.noNaNs() && FMF.noSignedZeros())
5300     return X;
5301 
5302   return nullptr;
5303 }
5304 
5305 /// Given the operands for an FMul, see if we can fold the result
5306 static Value *
5307 simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5308                  const SimplifyQuery &Q, unsigned MaxRecurse,
5309                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5310                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5311   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5312     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5313       return C;
5314 
5315   // Now apply simplifications that do not require rounding.
5316   return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5317 }
5318 
5319 Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5320                               const SimplifyQuery &Q,
5321                               fp::ExceptionBehavior ExBehavior,
5322                               RoundingMode Rounding) {
5323   return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5324                             Rounding);
5325 }
5326 
5327 Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5328                               const SimplifyQuery &Q,
5329                               fp::ExceptionBehavior ExBehavior,
5330                               RoundingMode Rounding) {
5331   return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5332                             Rounding);
5333 }
5334 
5335 Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5336                               const SimplifyQuery &Q,
5337                               fp::ExceptionBehavior ExBehavior,
5338                               RoundingMode Rounding) {
5339   return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5340                             Rounding);
5341 }
5342 
5343 Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5344                              const SimplifyQuery &Q,
5345                              fp::ExceptionBehavior ExBehavior,
5346                              RoundingMode Rounding) {
5347   return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5348                            Rounding);
5349 }
5350 
5351 static Value *
5352 simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5353                  const SimplifyQuery &Q, unsigned,
5354                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5355                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5356   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5357     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5358       return C;
5359 
5360   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5361     return C;
5362 
5363   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5364     return nullptr;
5365 
5366   // X / 1.0 -> X
5367   if (match(Op1, m_FPOne()))
5368     return Op0;
5369 
5370   // 0 / X -> 0
5371   // Requires that NaNs are off (X could be zero) and signed zeroes are
5372   // ignored (X could be positive or negative, so the output sign is unknown).
5373   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5374     return ConstantFP::getNullValue(Op0->getType());
5375 
5376   if (FMF.noNaNs()) {
5377     // X / X -> 1.0 is legal when NaNs are ignored.
5378     // We can ignore infinities because INF/INF is NaN.
5379     if (Op0 == Op1)
5380       return ConstantFP::get(Op0->getType(), 1.0);
5381 
5382     // (X * Y) / Y --> X if we can reassociate to the above form.
5383     Value *X;
5384     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5385       return X;
5386 
5387     // -X /  X -> -1.0 and
5388     //  X / -X -> -1.0 are legal when NaNs are ignored.
5389     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5390     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5391         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5392       return ConstantFP::get(Op0->getType(), -1.0);
5393   }
5394 
5395   return nullptr;
5396 }
5397 
5398 Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5399                               const SimplifyQuery &Q,
5400                               fp::ExceptionBehavior ExBehavior,
5401                               RoundingMode Rounding) {
5402   return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5403                             Rounding);
5404 }
5405 
5406 static Value *
5407 simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5408                  const SimplifyQuery &Q, unsigned,
5409                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5410                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5411   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5412     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5413       return C;
5414 
5415   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5416     return C;
5417 
5418   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5419     return nullptr;
5420 
5421   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5422   // The constant match may include undef elements in a vector, so return a full
5423   // zero constant as the result.
5424   if (FMF.noNaNs()) {
5425     // +0 % X -> 0
5426     if (match(Op0, m_PosZeroFP()))
5427       return ConstantFP::getNullValue(Op0->getType());
5428     // -0 % X -> -0
5429     if (match(Op0, m_NegZeroFP()))
5430       return ConstantFP::getNegativeZero(Op0->getType());
5431   }
5432 
5433   return nullptr;
5434 }
5435 
5436 Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5437                               const SimplifyQuery &Q,
5438                               fp::ExceptionBehavior ExBehavior,
5439                               RoundingMode Rounding) {
5440   return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5441                             Rounding);
5442 }
5443 
5444 //=== Helper functions for higher up the class hierarchy.
5445 
5446 /// Given the operand for a UnaryOperator, see if we can fold the result.
5447 /// If not, this returns null.
5448 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5449                            unsigned MaxRecurse) {
5450   switch (Opcode) {
5451   case Instruction::FNeg:
5452     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5453   default:
5454     llvm_unreachable("Unexpected opcode");
5455   }
5456 }
5457 
5458 /// Given the operand for a UnaryOperator, see if we can fold the result.
5459 /// If not, this returns null.
5460 /// Try to use FastMathFlags when folding the result.
5461 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5462                              const FastMathFlags &FMF, const SimplifyQuery &Q,
5463                              unsigned MaxRecurse) {
5464   switch (Opcode) {
5465   case Instruction::FNeg:
5466     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5467   default:
5468     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5469   }
5470 }
5471 
5472 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5473   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5474 }
5475 
5476 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5477                           const SimplifyQuery &Q) {
5478   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5479 }
5480 
5481 /// Given operands for a BinaryOperator, see if we can fold the result.
5482 /// If not, this returns null.
5483 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5484                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5485   switch (Opcode) {
5486   case Instruction::Add:
5487     return simplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5488   case Instruction::Sub:
5489     return simplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5490   case Instruction::Mul:
5491     return simplifyMulInst(LHS, RHS, Q, MaxRecurse);
5492   case Instruction::SDiv:
5493     return simplifySDivInst(LHS, RHS, Q, MaxRecurse);
5494   case Instruction::UDiv:
5495     return simplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5496   case Instruction::SRem:
5497     return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
5498   case Instruction::URem:
5499     return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
5500   case Instruction::Shl:
5501     return simplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5502   case Instruction::LShr:
5503     return simplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5504   case Instruction::AShr:
5505     return simplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5506   case Instruction::And:
5507     return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
5508   case Instruction::Or:
5509     return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
5510   case Instruction::Xor:
5511     return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
5512   case Instruction::FAdd:
5513     return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5514   case Instruction::FSub:
5515     return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5516   case Instruction::FMul:
5517     return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5518   case Instruction::FDiv:
5519     return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5520   case Instruction::FRem:
5521     return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5522   default:
5523     llvm_unreachable("Unexpected opcode");
5524   }
5525 }
5526 
5527 /// Given operands for a BinaryOperator, see if we can fold the result.
5528 /// If not, this returns null.
5529 /// Try to use FastMathFlags when folding the result.
5530 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5531                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5532                             unsigned MaxRecurse) {
5533   switch (Opcode) {
5534   case Instruction::FAdd:
5535     return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5536   case Instruction::FSub:
5537     return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5538   case Instruction::FMul:
5539     return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5540   case Instruction::FDiv:
5541     return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5542   default:
5543     return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5544   }
5545 }
5546 
5547 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5548                            const SimplifyQuery &Q) {
5549   return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5550 }
5551 
5552 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5553                            FastMathFlags FMF, const SimplifyQuery &Q) {
5554   return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5555 }
5556 
5557 /// Given operands for a CmpInst, see if we can fold the result.
5558 static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5559                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5560   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5561     return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5562   return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5563 }
5564 
5565 Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5566                              const SimplifyQuery &Q) {
5567   return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5568 }
5569 
5570 static bool isIdempotent(Intrinsic::ID ID) {
5571   switch (ID) {
5572   default:
5573     return false;
5574 
5575   // Unary idempotent: f(f(x)) = f(x)
5576   case Intrinsic::fabs:
5577   case Intrinsic::floor:
5578   case Intrinsic::ceil:
5579   case Intrinsic::trunc:
5580   case Intrinsic::rint:
5581   case Intrinsic::nearbyint:
5582   case Intrinsic::round:
5583   case Intrinsic::roundeven:
5584   case Intrinsic::canonicalize:
5585     return true;
5586   }
5587 }
5588 
5589 static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5590                                    const DataLayout &DL) {
5591   GlobalValue *PtrSym;
5592   APInt PtrOffset;
5593   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5594     return nullptr;
5595 
5596   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5597   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5598   Type *Int32PtrTy = Int32Ty->getPointerTo();
5599   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5600 
5601   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5602   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5603     return nullptr;
5604 
5605   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5606   if (OffsetInt % 4 != 0)
5607     return nullptr;
5608 
5609   Constant *C = ConstantExpr::getGetElementPtr(
5610       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5611       ConstantInt::get(Int64Ty, OffsetInt / 4));
5612   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5613   if (!Loaded)
5614     return nullptr;
5615 
5616   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5617   if (!LoadedCE)
5618     return nullptr;
5619 
5620   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5621     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5622     if (!LoadedCE)
5623       return nullptr;
5624   }
5625 
5626   if (LoadedCE->getOpcode() != Instruction::Sub)
5627     return nullptr;
5628 
5629   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5630   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5631     return nullptr;
5632   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5633 
5634   Constant *LoadedRHS = LoadedCE->getOperand(1);
5635   GlobalValue *LoadedRHSSym;
5636   APInt LoadedRHSOffset;
5637   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5638                                   DL) ||
5639       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5640     return nullptr;
5641 
5642   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5643 }
5644 
5645 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5646                                      const SimplifyQuery &Q) {
5647   // Idempotent functions return the same result when called repeatedly.
5648   Intrinsic::ID IID = F->getIntrinsicID();
5649   if (isIdempotent(IID))
5650     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5651       if (II->getIntrinsicID() == IID)
5652         return II;
5653 
5654   Value *X;
5655   switch (IID) {
5656   case Intrinsic::fabs:
5657     if (SignBitMustBeZero(Op0, Q.TLI))
5658       return Op0;
5659     break;
5660   case Intrinsic::bswap:
5661     // bswap(bswap(x)) -> x
5662     if (match(Op0, m_BSwap(m_Value(X))))
5663       return X;
5664     break;
5665   case Intrinsic::bitreverse:
5666     // bitreverse(bitreverse(x)) -> x
5667     if (match(Op0, m_BitReverse(m_Value(X))))
5668       return X;
5669     break;
5670   case Intrinsic::ctpop: {
5671     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5672     // ctpop(and X, 1) --> and X, 1
5673     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5674     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5675                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5676       return Op0;
5677     break;
5678   }
5679   case Intrinsic::exp:
5680     // exp(log(x)) -> x
5681     if (Q.CxtI->hasAllowReassoc() &&
5682         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
5683       return X;
5684     break;
5685   case Intrinsic::exp2:
5686     // exp2(log2(x)) -> x
5687     if (Q.CxtI->hasAllowReassoc() &&
5688         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
5689       return X;
5690     break;
5691   case Intrinsic::log:
5692     // log(exp(x)) -> x
5693     if (Q.CxtI->hasAllowReassoc() &&
5694         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
5695       return X;
5696     break;
5697   case Intrinsic::log2:
5698     // log2(exp2(x)) -> x
5699     if (Q.CxtI->hasAllowReassoc() &&
5700         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5701          match(Op0,
5702                m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
5703       return X;
5704     break;
5705   case Intrinsic::log10:
5706     // log10(pow(10.0, x)) -> x
5707     if (Q.CxtI->hasAllowReassoc() &&
5708         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X))))
5709       return X;
5710     break;
5711   case Intrinsic::floor:
5712   case Intrinsic::trunc:
5713   case Intrinsic::ceil:
5714   case Intrinsic::round:
5715   case Intrinsic::roundeven:
5716   case Intrinsic::nearbyint:
5717   case Intrinsic::rint: {
5718     // floor (sitofp x) -> sitofp x
5719     // floor (uitofp x) -> uitofp x
5720     //
5721     // Converting from int always results in a finite integral number or
5722     // infinity. For either of those inputs, these rounding functions always
5723     // return the same value, so the rounding can be eliminated.
5724     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5725       return Op0;
5726     break;
5727   }
5728   case Intrinsic::experimental_vector_reverse:
5729     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5730     if (match(Op0,
5731               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5732       return X;
5733     // experimental.vector.reverse(splat(X)) -> splat(X)
5734     if (isSplatValue(Op0))
5735       return Op0;
5736     break;
5737   default:
5738     break;
5739   }
5740 
5741   return nullptr;
5742 }
5743 
5744 /// Given a min/max intrinsic, see if it can be removed based on having an
5745 /// operand that is another min/max intrinsic with shared operand(s). The caller
5746 /// is expected to swap the operand arguments to handle commutation.
5747 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5748   Value *X, *Y;
5749   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5750     return nullptr;
5751 
5752   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5753   if (!MM0)
5754     return nullptr;
5755   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5756 
5757   if (Op1 == X || Op1 == Y ||
5758       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5759     // max (max X, Y), X --> max X, Y
5760     if (IID0 == IID)
5761       return MM0;
5762     // max (min X, Y), X --> X
5763     if (IID0 == getInverseMinMaxIntrinsic(IID))
5764       return Op1;
5765   }
5766   return nullptr;
5767 }
5768 
5769 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5770                                       const SimplifyQuery &Q) {
5771   Intrinsic::ID IID = F->getIntrinsicID();
5772   Type *ReturnType = F->getReturnType();
5773   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5774   switch (IID) {
5775   case Intrinsic::abs:
5776     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5777     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5778     // on the outer abs.
5779     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5780       return Op0;
5781     break;
5782 
5783   case Intrinsic::cttz: {
5784     Value *X;
5785     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5786       return X;
5787     break;
5788   }
5789   case Intrinsic::ctlz: {
5790     Value *X;
5791     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
5792       return X;
5793     if (match(Op0, m_AShr(m_Negative(), m_Value())))
5794       return Constant::getNullValue(ReturnType);
5795     break;
5796   }
5797   case Intrinsic::smax:
5798   case Intrinsic::smin:
5799   case Intrinsic::umax:
5800   case Intrinsic::umin: {
5801     // If the arguments are the same, this is a no-op.
5802     if (Op0 == Op1)
5803       return Op0;
5804 
5805     // Canonicalize constant operand as Op1.
5806     if (isa<Constant>(Op0))
5807       std::swap(Op0, Op1);
5808 
5809     // Assume undef is the limit value.
5810     if (Q.isUndefValue(Op1))
5811       return ConstantInt::get(
5812           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
5813 
5814     const APInt *C;
5815     if (match(Op1, m_APIntAllowUndef(C))) {
5816       // Clamp to limit value. For example:
5817       // umax(i8 %x, i8 255) --> 255
5818       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
5819         return ConstantInt::get(ReturnType, *C);
5820 
5821       // If the constant op is the opposite of the limit value, the other must
5822       // be larger/smaller or equal. For example:
5823       // umin(i8 %x, i8 255) --> %x
5824       if (*C == MinMaxIntrinsic::getSaturationPoint(
5825                     getInverseMinMaxIntrinsic(IID), BitWidth))
5826         return Op0;
5827 
5828       // Remove nested call if constant operands allow it. Example:
5829       // max (max X, 7), 5 -> max X, 7
5830       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5831       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5832         // TODO: loosen undef/splat restrictions for vector constants.
5833         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5834         const APInt *InnerC;
5835         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5836             ICmpInst::compare(*InnerC, *C,
5837                               ICmpInst::getNonStrictPredicate(
5838                                   MinMaxIntrinsic::getPredicate(IID))))
5839           return Op0;
5840       }
5841     }
5842 
5843     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5844       return V;
5845     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5846       return V;
5847 
5848     ICmpInst::Predicate Pred =
5849         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
5850     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5851       return Op0;
5852     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5853       return Op1;
5854 
5855     if (Optional<bool> Imp =
5856             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5857       return *Imp ? Op0 : Op1;
5858     if (Optional<bool> Imp =
5859             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5860       return *Imp ? Op1 : Op0;
5861 
5862     break;
5863   }
5864   case Intrinsic::usub_with_overflow:
5865   case Intrinsic::ssub_with_overflow:
5866     // X - X -> { 0, false }
5867     // X - undef -> { 0, false }
5868     // undef - X -> { 0, false }
5869     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5870       return Constant::getNullValue(ReturnType);
5871     break;
5872   case Intrinsic::uadd_with_overflow:
5873   case Intrinsic::sadd_with_overflow:
5874     // X + undef -> { -1, false }
5875     // undef + x -> { -1, false }
5876     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5877       return ConstantStruct::get(
5878           cast<StructType>(ReturnType),
5879           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5880            Constant::getNullValue(ReturnType->getStructElementType(1))});
5881     }
5882     break;
5883   case Intrinsic::umul_with_overflow:
5884   case Intrinsic::smul_with_overflow:
5885     // 0 * X -> { 0, false }
5886     // X * 0 -> { 0, false }
5887     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5888       return Constant::getNullValue(ReturnType);
5889     // undef * X -> { 0, false }
5890     // X * undef -> { 0, false }
5891     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5892       return Constant::getNullValue(ReturnType);
5893     break;
5894   case Intrinsic::uadd_sat:
5895     // sat(MAX + X) -> MAX
5896     // sat(X + MAX) -> MAX
5897     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5898       return Constant::getAllOnesValue(ReturnType);
5899     LLVM_FALLTHROUGH;
5900   case Intrinsic::sadd_sat:
5901     // sat(X + undef) -> -1
5902     // sat(undef + X) -> -1
5903     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5904     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5905     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5906       return Constant::getAllOnesValue(ReturnType);
5907 
5908     // X + 0 -> X
5909     if (match(Op1, m_Zero()))
5910       return Op0;
5911     // 0 + X -> X
5912     if (match(Op0, m_Zero()))
5913       return Op1;
5914     break;
5915   case Intrinsic::usub_sat:
5916     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5917     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5918       return Constant::getNullValue(ReturnType);
5919     LLVM_FALLTHROUGH;
5920   case Intrinsic::ssub_sat:
5921     // X - X -> 0, X - undef -> 0, undef - X -> 0
5922     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5923       return Constant::getNullValue(ReturnType);
5924     // X - 0 -> X
5925     if (match(Op1, m_Zero()))
5926       return Op0;
5927     break;
5928   case Intrinsic::load_relative:
5929     if (auto *C0 = dyn_cast<Constant>(Op0))
5930       if (auto *C1 = dyn_cast<Constant>(Op1))
5931         return simplifyRelativeLoad(C0, C1, Q.DL);
5932     break;
5933   case Intrinsic::powi:
5934     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5935       // powi(x, 0) -> 1.0
5936       if (Power->isZero())
5937         return ConstantFP::get(Op0->getType(), 1.0);
5938       // powi(x, 1) -> x
5939       if (Power->isOne())
5940         return Op0;
5941     }
5942     break;
5943   case Intrinsic::copysign:
5944     // copysign X, X --> X
5945     if (Op0 == Op1)
5946       return Op0;
5947     // copysign -X, X --> X
5948     // copysign X, -X --> -X
5949     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5950         match(Op1, m_FNeg(m_Specific(Op0))))
5951       return Op1;
5952     break;
5953   case Intrinsic::maxnum:
5954   case Intrinsic::minnum:
5955   case Intrinsic::maximum:
5956   case Intrinsic::minimum: {
5957     // If the arguments are the same, this is a no-op.
5958     if (Op0 == Op1)
5959       return Op0;
5960 
5961     // Canonicalize constant operand as Op1.
5962     if (isa<Constant>(Op0))
5963       std::swap(Op0, Op1);
5964 
5965     // If an argument is undef, return the other argument.
5966     if (Q.isUndefValue(Op1))
5967       return Op0;
5968 
5969     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5970     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5971 
5972     // minnum(X, nan) -> X
5973     // maxnum(X, nan) -> X
5974     // minimum(X, nan) -> nan
5975     // maximum(X, nan) -> nan
5976     if (match(Op1, m_NaN()))
5977       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5978 
5979     // In the following folds, inf can be replaced with the largest finite
5980     // float, if the ninf flag is set.
5981     const APFloat *C;
5982     if (match(Op1, m_APFloat(C)) &&
5983         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5984       // minnum(X, -inf) -> -inf
5985       // maxnum(X, +inf) -> +inf
5986       // minimum(X, -inf) -> -inf if nnan
5987       // maximum(X, +inf) -> +inf if nnan
5988       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5989         return ConstantFP::get(ReturnType, *C);
5990 
5991       // minnum(X, +inf) -> X if nnan
5992       // maxnum(X, -inf) -> X if nnan
5993       // minimum(X, +inf) -> X
5994       // maximum(X, -inf) -> X
5995       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5996         return Op0;
5997     }
5998 
5999     // Min/max of the same operation with common operand:
6000     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
6001     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
6002       if (M0->getIntrinsicID() == IID &&
6003           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
6004         return Op0;
6005     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
6006       if (M1->getIntrinsicID() == IID &&
6007           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
6008         return Op1;
6009 
6010     break;
6011   }
6012   case Intrinsic::experimental_vector_extract: {
6013     Type *ReturnType = F->getReturnType();
6014 
6015     // (extract_vector (insert_vector _, X, 0), 0) -> X
6016     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
6017     Value *X = nullptr;
6018     if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>(
6019                        m_Value(), m_Value(X), m_Zero())) &&
6020         IdxN == 0 && X->getType() == ReturnType)
6021       return X;
6022 
6023     break;
6024   }
6025   default:
6026     break;
6027   }
6028 
6029   return nullptr;
6030 }
6031 
6032 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
6033 
6034   unsigned NumOperands = Call->arg_size();
6035   Function *F = cast<Function>(Call->getCalledFunction());
6036   Intrinsic::ID IID = F->getIntrinsicID();
6037 
6038   // Most of the intrinsics with no operands have some kind of side effect.
6039   // Don't simplify.
6040   if (!NumOperands) {
6041     switch (IID) {
6042     case Intrinsic::vscale: {
6043       // Call may not be inserted into the IR yet at point of calling simplify.
6044       if (!Call->getParent() || !Call->getParent()->getParent())
6045         return nullptr;
6046       auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
6047       if (!Attr.isValid())
6048         return nullptr;
6049       unsigned VScaleMin = Attr.getVScaleRangeMin();
6050       Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
6051       if (VScaleMax && VScaleMin == VScaleMax)
6052         return ConstantInt::get(F->getReturnType(), VScaleMin);
6053       return nullptr;
6054     }
6055     default:
6056       return nullptr;
6057     }
6058   }
6059 
6060   if (NumOperands == 1)
6061     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
6062 
6063   if (NumOperands == 2)
6064     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
6065                                    Call->getArgOperand(1), Q);
6066 
6067   // Handle intrinsics with 3 or more arguments.
6068   switch (IID) {
6069   case Intrinsic::masked_load:
6070   case Intrinsic::masked_gather: {
6071     Value *MaskArg = Call->getArgOperand(2);
6072     Value *PassthruArg = Call->getArgOperand(3);
6073     // If the mask is all zeros or undef, the "passthru" argument is the result.
6074     if (maskIsAllZeroOrUndef(MaskArg))
6075       return PassthruArg;
6076     return nullptr;
6077   }
6078   case Intrinsic::fshl:
6079   case Intrinsic::fshr: {
6080     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
6081           *ShAmtArg = Call->getArgOperand(2);
6082 
6083     // If both operands are undef, the result is undef.
6084     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
6085       return UndefValue::get(F->getReturnType());
6086 
6087     // If shift amount is undef, assume it is zero.
6088     if (Q.isUndefValue(ShAmtArg))
6089       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6090 
6091     const APInt *ShAmtC;
6092     if (match(ShAmtArg, m_APInt(ShAmtC))) {
6093       // If there's effectively no shift, return the 1st arg or 2nd arg.
6094       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6095       if (ShAmtC->urem(BitWidth).isZero())
6096         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6097     }
6098 
6099     // Rotating zero by anything is zero.
6100     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6101       return ConstantInt::getNullValue(F->getReturnType());
6102 
6103     // Rotating -1 by anything is -1.
6104     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6105       return ConstantInt::getAllOnesValue(F->getReturnType());
6106 
6107     return nullptr;
6108   }
6109   case Intrinsic::experimental_constrained_fma: {
6110     Value *Op0 = Call->getArgOperand(0);
6111     Value *Op1 = Call->getArgOperand(1);
6112     Value *Op2 = Call->getArgOperand(2);
6113     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6114     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
6115                                 FPI->getExceptionBehavior().getValue(),
6116                                 FPI->getRoundingMode().getValue()))
6117       return V;
6118     return nullptr;
6119   }
6120   case Intrinsic::fma:
6121   case Intrinsic::fmuladd: {
6122     Value *Op0 = Call->getArgOperand(0);
6123     Value *Op1 = Call->getArgOperand(1);
6124     Value *Op2 = Call->getArgOperand(2);
6125     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
6126                                 RoundingMode::NearestTiesToEven))
6127       return V;
6128     return nullptr;
6129   }
6130   case Intrinsic::smul_fix:
6131   case Intrinsic::smul_fix_sat: {
6132     Value *Op0 = Call->getArgOperand(0);
6133     Value *Op1 = Call->getArgOperand(1);
6134     Value *Op2 = Call->getArgOperand(2);
6135     Type *ReturnType = F->getReturnType();
6136 
6137     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6138     // when both Op0 and Op1 are constant so we do not care about that special
6139     // case here).
6140     if (isa<Constant>(Op0))
6141       std::swap(Op0, Op1);
6142 
6143     // X * 0 -> 0
6144     if (match(Op1, m_Zero()))
6145       return Constant::getNullValue(ReturnType);
6146 
6147     // X * undef -> 0
6148     if (Q.isUndefValue(Op1))
6149       return Constant::getNullValue(ReturnType);
6150 
6151     // X * (1 << Scale) -> X
6152     APInt ScaledOne =
6153         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6154                             cast<ConstantInt>(Op2)->getZExtValue());
6155     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6156       return Op0;
6157 
6158     return nullptr;
6159   }
6160   case Intrinsic::experimental_vector_insert: {
6161     Value *Vec = Call->getArgOperand(0);
6162     Value *SubVec = Call->getArgOperand(1);
6163     Value *Idx = Call->getArgOperand(2);
6164     Type *ReturnType = F->getReturnType();
6165 
6166     // (insert_vector Y, (extract_vector X, 0), 0) -> X
6167     // where: Y is X, or Y is undef
6168     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6169     Value *X = nullptr;
6170     if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>(
6171                           m_Value(X), m_Zero())) &&
6172         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6173         X->getType() == ReturnType)
6174       return X;
6175 
6176     return nullptr;
6177   }
6178   case Intrinsic::experimental_constrained_fadd: {
6179     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6180     return simplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6181                             FPI->getFastMathFlags(), Q,
6182                             FPI->getExceptionBehavior().getValue(),
6183                             FPI->getRoundingMode().getValue());
6184   }
6185   case Intrinsic::experimental_constrained_fsub: {
6186     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6187     return simplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6188                             FPI->getFastMathFlags(), Q,
6189                             FPI->getExceptionBehavior().getValue(),
6190                             FPI->getRoundingMode().getValue());
6191   }
6192   case Intrinsic::experimental_constrained_fmul: {
6193     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6194     return simplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6195                             FPI->getFastMathFlags(), Q,
6196                             FPI->getExceptionBehavior().getValue(),
6197                             FPI->getRoundingMode().getValue());
6198   }
6199   case Intrinsic::experimental_constrained_fdiv: {
6200     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6201     return simplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6202                             FPI->getFastMathFlags(), Q,
6203                             FPI->getExceptionBehavior().getValue(),
6204                             FPI->getRoundingMode().getValue());
6205   }
6206   case Intrinsic::experimental_constrained_frem: {
6207     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6208     return simplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6209                             FPI->getFastMathFlags(), Q,
6210                             FPI->getExceptionBehavior().getValue(),
6211                             FPI->getRoundingMode().getValue());
6212   }
6213   default:
6214     return nullptr;
6215   }
6216 }
6217 
6218 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
6219   auto *F = dyn_cast<Function>(Call->getCalledOperand());
6220   if (!F || !canConstantFoldCallTo(Call, F))
6221     return nullptr;
6222 
6223   SmallVector<Constant *, 4> ConstantArgs;
6224   unsigned NumArgs = Call->arg_size();
6225   ConstantArgs.reserve(NumArgs);
6226   for (auto &Arg : Call->args()) {
6227     Constant *C = dyn_cast<Constant>(&Arg);
6228     if (!C) {
6229       if (isa<MetadataAsValue>(Arg.get()))
6230         continue;
6231       return nullptr;
6232     }
6233     ConstantArgs.push_back(C);
6234   }
6235 
6236   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6237 }
6238 
6239 Value *llvm::simplifyCall(CallBase *Call, const SimplifyQuery &Q) {
6240   // musttail calls can only be simplified if they are also DCEd.
6241   // As we can't guarantee this here, don't simplify them.
6242   if (Call->isMustTailCall())
6243     return nullptr;
6244 
6245   // call undef -> poison
6246   // call null -> poison
6247   Value *Callee = Call->getCalledOperand();
6248   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6249     return PoisonValue::get(Call->getType());
6250 
6251   if (Value *V = tryConstantFoldCall(Call, Q))
6252     return V;
6253 
6254   auto *F = dyn_cast<Function>(Callee);
6255   if (F && F->isIntrinsic())
6256     if (Value *Ret = simplifyIntrinsic(Call, Q))
6257       return Ret;
6258 
6259   return nullptr;
6260 }
6261 
6262 Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
6263   assert(isa<ConstrainedFPIntrinsic>(Call));
6264   if (Value *V = tryConstantFoldCall(Call, Q))
6265     return V;
6266   if (Value *Ret = simplifyIntrinsic(Call, Q))
6267     return Ret;
6268   return nullptr;
6269 }
6270 
6271 /// Given operands for a Freeze, see if we can fold the result.
6272 static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6273   // Use a utility function defined in ValueTracking.
6274   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6275     return Op0;
6276   // We have room for improvement.
6277   return nullptr;
6278 }
6279 
6280 Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6281   return ::simplifyFreezeInst(Op0, Q);
6282 }
6283 
6284 static Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
6285                                const SimplifyQuery &Q) {
6286   if (LI->isVolatile())
6287     return nullptr;
6288 
6289   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
6290   auto *PtrOpC = dyn_cast<Constant>(PtrOp);
6291   // Try to convert operand into a constant by stripping offsets while looking
6292   // through invariant.group intrinsics. Don't bother if the underlying object
6293   // is not constant, as calculating GEP offsets is expensive.
6294   if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
6295     PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6296         Q.DL, Offset, /* AllowNonInbounts */ true,
6297         /* AllowInvariantGroup */ true);
6298     // Index size may have changed due to address space casts.
6299     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6300     PtrOpC = dyn_cast<Constant>(PtrOp);
6301   }
6302 
6303   if (PtrOpC)
6304     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
6305   return nullptr;
6306 }
6307 
6308 /// See if we can compute a simplified version of this instruction.
6309 /// If not, this returns null.
6310 
6311 static Value *simplifyInstructionWithOperands(Instruction *I,
6312                                               ArrayRef<Value *> NewOps,
6313                                               const SimplifyQuery &SQ,
6314                                               OptimizationRemarkEmitter *ORE) {
6315   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
6316   Value *Result = nullptr;
6317 
6318   switch (I->getOpcode()) {
6319   default:
6320     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
6321       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
6322       transform(NewOps, NewConstOps.begin(),
6323                 [](Value *V) { return cast<Constant>(V); });
6324       Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
6325     }
6326     break;
6327   case Instruction::FNeg:
6328     Result = simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
6329     break;
6330   case Instruction::FAdd:
6331     Result = simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6332     break;
6333   case Instruction::Add:
6334     Result = simplifyAddInst(
6335         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6336         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6337     break;
6338   case Instruction::FSub:
6339     Result = simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6340     break;
6341   case Instruction::Sub:
6342     Result = simplifySubInst(
6343         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6344         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6345     break;
6346   case Instruction::FMul:
6347     Result = simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6348     break;
6349   case Instruction::Mul:
6350     Result = simplifyMulInst(NewOps[0], NewOps[1], Q);
6351     break;
6352   case Instruction::SDiv:
6353     Result = simplifySDivInst(NewOps[0], NewOps[1], Q);
6354     break;
6355   case Instruction::UDiv:
6356     Result = simplifyUDivInst(NewOps[0], NewOps[1], Q);
6357     break;
6358   case Instruction::FDiv:
6359     Result = simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6360     break;
6361   case Instruction::SRem:
6362     Result = simplifySRemInst(NewOps[0], NewOps[1], Q);
6363     break;
6364   case Instruction::URem:
6365     Result = simplifyURemInst(NewOps[0], NewOps[1], Q);
6366     break;
6367   case Instruction::FRem:
6368     Result = simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6369     break;
6370   case Instruction::Shl:
6371     Result = simplifyShlInst(
6372         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6373         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6374     break;
6375   case Instruction::LShr:
6376     Result = simplifyLShrInst(NewOps[0], NewOps[1],
6377                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6378     break;
6379   case Instruction::AShr:
6380     Result = simplifyAShrInst(NewOps[0], NewOps[1],
6381                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6382     break;
6383   case Instruction::And:
6384     Result = simplifyAndInst(NewOps[0], NewOps[1], Q);
6385     break;
6386   case Instruction::Or:
6387     Result = simplifyOrInst(NewOps[0], NewOps[1], Q);
6388     break;
6389   case Instruction::Xor:
6390     Result = simplifyXorInst(NewOps[0], NewOps[1], Q);
6391     break;
6392   case Instruction::ICmp:
6393     Result = simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
6394                               NewOps[1], Q);
6395     break;
6396   case Instruction::FCmp:
6397     Result = simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
6398                               NewOps[1], I->getFastMathFlags(), Q);
6399     break;
6400   case Instruction::Select:
6401     Result = simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
6402     break;
6403   case Instruction::GetElementPtr: {
6404     auto *GEPI = cast<GetElementPtrInst>(I);
6405     Result =
6406         simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
6407                         makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
6408     break;
6409   }
6410   case Instruction::InsertValue: {
6411     InsertValueInst *IV = cast<InsertValueInst>(I);
6412     Result = simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
6413     break;
6414   }
6415   case Instruction::InsertElement: {
6416     Result = simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
6417     break;
6418   }
6419   case Instruction::ExtractValue: {
6420     auto *EVI = cast<ExtractValueInst>(I);
6421     Result = simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
6422     break;
6423   }
6424   case Instruction::ExtractElement: {
6425     Result = simplifyExtractElementInst(NewOps[0], NewOps[1], Q);
6426     break;
6427   }
6428   case Instruction::ShuffleVector: {
6429     auto *SVI = cast<ShuffleVectorInst>(I);
6430     Result = simplifyShuffleVectorInst(
6431         NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q);
6432     break;
6433   }
6434   case Instruction::PHI:
6435     Result = simplifyPHINode(cast<PHINode>(I), NewOps, Q);
6436     break;
6437   case Instruction::Call: {
6438     // TODO: Use NewOps
6439     Result = simplifyCall(cast<CallInst>(I), Q);
6440     break;
6441   }
6442   case Instruction::Freeze:
6443     Result = llvm::simplifyFreezeInst(NewOps[0], Q);
6444     break;
6445 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
6446 #include "llvm/IR/Instruction.def"
6447 #undef HANDLE_CAST_INST
6448     Result = simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
6449     break;
6450   case Instruction::Alloca:
6451     // No simplifications for Alloca and it can't be constant folded.
6452     Result = nullptr;
6453     break;
6454   case Instruction::Load:
6455     Result = simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
6456     break;
6457   }
6458 
6459   /// If called on unreachable code, the above logic may report that the
6460   /// instruction simplified to itself.  Make life easier for users by
6461   /// detecting that case here, returning a safe value instead.
6462   return Result == I ? UndefValue::get(I->getType()) : Result;
6463 }
6464 
6465 Value *llvm::simplifyInstructionWithOperands(Instruction *I,
6466                                              ArrayRef<Value *> NewOps,
6467                                              const SimplifyQuery &SQ,
6468                                              OptimizationRemarkEmitter *ORE) {
6469   assert(NewOps.size() == I->getNumOperands() &&
6470          "Number of operands should match the instruction!");
6471   return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
6472 }
6473 
6474 Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
6475                                  OptimizationRemarkEmitter *ORE) {
6476   SmallVector<Value *, 8> Ops(I->operands());
6477   return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
6478 }
6479 
6480 /// Implementation of recursive simplification through an instruction's
6481 /// uses.
6482 ///
6483 /// This is the common implementation of the recursive simplification routines.
6484 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
6485 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
6486 /// instructions to process and attempt to simplify it using
6487 /// InstructionSimplify. Recursively visited users which could not be
6488 /// simplified themselves are to the optional UnsimplifiedUsers set for
6489 /// further processing by the caller.
6490 ///
6491 /// This routine returns 'true' only when *it* simplifies something. The passed
6492 /// in simplified value does not count toward this.
6493 static bool replaceAndRecursivelySimplifyImpl(
6494     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6495     const DominatorTree *DT, AssumptionCache *AC,
6496     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
6497   bool Simplified = false;
6498   SmallSetVector<Instruction *, 8> Worklist;
6499   const DataLayout &DL = I->getModule()->getDataLayout();
6500 
6501   // If we have an explicit value to collapse to, do that round of the
6502   // simplification loop by hand initially.
6503   if (SimpleV) {
6504     for (User *U : I->users())
6505       if (U != I)
6506         Worklist.insert(cast<Instruction>(U));
6507 
6508     // Replace the instruction with its simplified value.
6509     I->replaceAllUsesWith(SimpleV);
6510 
6511     // Gracefully handle edge cases where the instruction is not wired into any
6512     // parent block.
6513     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6514         !I->mayHaveSideEffects())
6515       I->eraseFromParent();
6516   } else {
6517     Worklist.insert(I);
6518   }
6519 
6520   // Note that we must test the size on each iteration, the worklist can grow.
6521   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6522     I = Worklist[Idx];
6523 
6524     // See if this instruction simplifies.
6525     SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
6526     if (!SimpleV) {
6527       if (UnsimplifiedUsers)
6528         UnsimplifiedUsers->insert(I);
6529       continue;
6530     }
6531 
6532     Simplified = true;
6533 
6534     // Stash away all the uses of the old instruction so we can check them for
6535     // recursive simplifications after a RAUW. This is cheaper than checking all
6536     // uses of To on the recursive step in most cases.
6537     for (User *U : I->users())
6538       Worklist.insert(cast<Instruction>(U));
6539 
6540     // Replace the instruction with its simplified value.
6541     I->replaceAllUsesWith(SimpleV);
6542 
6543     // Gracefully handle edge cases where the instruction is not wired into any
6544     // parent block.
6545     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6546         !I->mayHaveSideEffects())
6547       I->eraseFromParent();
6548   }
6549   return Simplified;
6550 }
6551 
6552 bool llvm::replaceAndRecursivelySimplify(
6553     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6554     const DominatorTree *DT, AssumptionCache *AC,
6555     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6556   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6557   assert(SimpleV && "Must provide a simplified value.");
6558   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6559                                            UnsimplifiedUsers);
6560 }
6561 
6562 namespace llvm {
6563 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6564   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6565   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6566   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6567   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6568   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6569   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6570   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6571 }
6572 
6573 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6574                                          const DataLayout &DL) {
6575   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6576 }
6577 
6578 template <class T, class... TArgs>
6579 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6580                                          Function &F) {
6581   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6582   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6583   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6584   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6585 }
6586 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6587                                                   Function &);
6588 } // namespace llvm
6589 
6590 void InstSimplifyFolder::anchor() {}
6591