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