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