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